Magicsheet logo

Print Words Vertically

Medium
89.3%
Updated 6/1/2025

Asked by 2 Companies

Print Words Vertically

What is this problem about?

The Print Words Vertically problem gives you a sentence string and asks you to print the words vertically — character by character column by column, where each "column" contains the characters at position i from each word. Shorter words get spaces padded, but trailing spaces in each column should be removed. This coding problem tests matrix transposition with trailing space trimming. The array, string, and simulation interview pattern is the core.

Why is this asked in interviews?

Microsoft asks this to test string manipulation — specifically the ability to handle ragged column lengths and trim trailing spaces correctly. It's a simulation problem that requires careful indexing and output formatting.

Algorithmic pattern used

Transposition with rstrip. Split sentence into words. Find max_len = maximum word length. For each column i from 0 to max_len-1: build the vertical string by taking character i from each word (or space if word is shorter). Right-strip the resulting string. Add to results.

Example explanation

s="TO BE OR NOT TO GO". Words=["TO","BE","OR","NOT","TO","GO"]. Max length = 3 (NOT).

  • Column 0: T,B,O,N,T,G → "TBONTG".
  • Column 1: O,E,R,O,O,O → "OEROOO".
  • Column 2: ' ',' ',' ',T,' ',' ' → " T " → rstrip → " T". Result: ["TBONTG","OEROOO"," T"].

Common mistakes candidates make

  • Not padding shorter words with spaces before transposing.
  • Forgetting to rstrip (keeping trailing spaces).
  • Off-by-one in max_len computation.
  • Using len(words) instead of max(len(w)) for the column count.

Interview preparation tip

Matrix transposition problems on strings require careful length handling. The "ragged columns" issue — words of different lengths — is handled by padding with spaces during column extraction. The rstrip at the end removes the padding that would be trailing. Practice similar "column-by-column extraction" problems: "transpose matrix," "rotate image," "diagonal traversal." Clean string construction with proper trimming is the key implementation skill.

Similar Questions