Print Words Vertically

Medium
1214.

Print Words Vertically

Print Words Vertically is a medium coding problem on arrays, strings and simulation, asked in Amazon and Microsoft interviews.

The string s holds words of uppercase letters separated by single spaces. Write the words vertically, side by side: the i-th output string is made of the i-th letter of every word, in word order, with a space standing in for a word that is too short to have an i-th letter.

There are as many output strings as the length of the longest word. Trailing spaces must be removed from every output string (spaces before a letter stay).

Example 1

Input
s = "CODE KAIRO"
Output
["CK","OA","DI","ER"," O"]
Explanation
`CODE` has no fifth letter, so the last row starts with a space.

Example 2

Input
s = "AI PAIR DUEL"
Output
["APD","IAU"," IE"," RL"]

Example 3

Input
s = "A BB C"
Output
["ABC"," B"]
Explanation
The second row is `" B "` before its trailing space is removed.

Constraints

  • 1 <= s.length <= 200
  • s contains only uppercase English letters and spaces
  • Words are separated by exactly one space
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} s
 * @return {string[]}
 */
var printVertically = function(s) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Print Words Vertically — Solution in Python, Java & C++

Print Words Vertically solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem.

Print Words Vertically is a medium coding problem on arrays, strings and simulation, asked in Amazon and Microsoft interviews.

  • Difficulty: Medium
  • Topics: Arrays, Strings, Simulation
  • Asked at: Amazon, Microsoft
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

The string s holds words of uppercase letters separated by single spaces. Write the words vertically, side by side: the i-th output string is made of the i-th letter of every word, in word order, with a space standing in for a word that is too short to have an i-th letter.

There are as many output strings as the length of the longest word. Trailing spaces must be removed from every output string (spaces before a letter stay).

Example 1

Input: s = "CODE KAIRO"
Output: ["CK","OA","DI","ER"," O"]
Explanation: `CODE` has no fifth letter, so the last row starts with a space.

Example 2

Input: s = "AI PAIR DUEL"
Output: ["APD","IAU"," IE"," RL"]

Example 3

Input: s = "A BB C"
Output: ["ABC"," B"]
Explanation: The second row is `" B "` before its trailing space is removed.

Constraints

  • 1 <= s.length <= 200
  • s contains only uppercase English letters and spaces
  • Words are separated by exactly one space

Hints for Print Words Vertically

  1. Hint 1

    Split s into words and find the longest word's length.

  2. Hint 2

    Row i takes word[i] from each word, or a space if the word is shorter.

  3. Hint 3

    Strip only the trailing spaces of each row.

How to solve Print Words Vertically

Treat the words as the columns of a ragged grid and read it row by row, padding missing cells with spaces and trimming each row's right end.

Approach

  1. Split s on spaces and let rows be the length of the longest word.
  2. For i from 0 to rows − 1, build a string of length wordCount whose j-th character is words[j][i] if it exists and a space otherwise.
  3. Remove the trailing spaces of that string and append it to the answer.

Why it works

Every letter of every word lands in exactly one row (its index) and one column (its word), so the rows are the vertical reading. Trailing spaces only come from words shorter than the row index at the right end; padding inside a row must stay so the letters keep their columns. No row becomes empty, because the longest word has a letter in every row.

Complexity

  • Time — O(rows · words)
  • Space — O(rows · words) for the output

Pitfalls

  • Trimming leading spaces too shifts letters into the wrong column.
  • Forgetting to trim leaves rows such as " B ".
  • Words are separated by exactly one space, so splitting on a single space yields no empty words.

Reference solution

Python

from typing import List

def printVertically(s: str) -> List[str]:
    words = s.split(" ")
    rows = max(len(w) for w in words)
    res = []
    for i in range(rows):
        row = "".join(w[i] if i < len(w) else " " for w in words)
        res.append(row.rstrip(" "))
    return res

Java

public static String[] printVertically(String s) {
    String[] words = s.split(" ");
    int rows = 0;
    for (String w : words) rows = Math.max(rows, w.length());
    String[] res = new String[rows];
    for (int i = 0; i < rows; i++) {
        StringBuilder sb = new StringBuilder();
        for (String w : words) sb.append(i < w.length() ? w.charAt(i) : ' ');
        int end = sb.length();
        while (end > 0 && sb.charAt(end - 1) == ' ') end--;
        res[i] = sb.substring(0, end);
    }
    return res;
}

C++

vector<string> printVertically(string s) {
    vector<string> words;
    stringstream ss(s);
    string w;
    size_t rows = 0;
    while (ss >> w) {
        rows = max(rows, w.size());
        words.push_back(w);
    }
    vector<string> res;
    for (size_t i = 0; i < rows; i++) {
        string row;
        for (const string& x : words) row.push_back(i < x.size() ? x[i] : ' ');
        while (!row.empty() && row.back() == ' ') row.pop_back();
        res.push_back(row);
    }
    return res;
}

JavaScript

var printVertically = function(s) {
    var words = s.split(" ");
    var rows = 0;
    for (var k = 0; k < words.length; k++) rows = Math.max(rows, words[k].length);
    var res = [];
    for (var i = 0; i < rows; i++) {
        var row = "";
        for (var j = 0; j < words.length; j++) row += i < words[j].length ? words[j][i] : " ";
        var end = row.length;
        while (end > 0 && row[end - 1] === " ") end--;
        res.push(row.substring(0, end));
    }
    return res;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 1199 arrays problems · the whole catalogue

Learn the technique: Arrays · Strings