Vertical Order Traversal in Strings

Given a string str consisting of multiple words separated by space, the task is to print the vertical order traversal of this string. Vertical order traversal refers to the row-wise traversal of the grid formed from the given string when each word is inserted in the grid in vertical order.
Note: A space(” “) is represented by a “$” symbol for better visualization.

Examples:

Input: str = “geeks for geeks”
Output: [gfg, eoe, ere, k$k, s$s]
Explanation: Vertical order of the string will result in the following column values.
g f g
e o e
e r e
k $ k
s $ s
Now the Answer will be a list of strings appearing row-wise.

Input: str = “ge ek sfor ge eks”
Output: [gesge, ekfek, $$o$s, $$r$$]



Approach: The idea is to use a HashMap where the key of the hashmap represents the index and the value represents the characters at that index. The following steps can be followed to compute the vertical order traversal.

  1. Split the given string into words.
    For example:

    If String is "Geeks For Geeks"
    then the words will be
    words = {"Geeks", "For", "Geeks"}
    
  2. Initially, the word with maximum length is found. All the words are then either less than or equal to this length.
  3. Then create a HashMap of the size of the maximum word.
    For example:

    If the maximum length word is 5,
    then the HashMap will be
    map = {
            {0, ""},
            {1, ""},
            {2, ""},
            {3, ""},
            {4, ""}
          }
    
  4. For every word, it is then checked whether the word is of this max length or not. If it is, then it is appended to the HashMap. Else, extra space (represented as “$“) is added to the string.
    For example:

    For String = "Geeks For Geeks"
    then the HashMap after word "Geeks"
    map = {
            {0, "G"},
            {1, "e"},
            {2, "e"},
            {3, "k"},
            {4, "s"}
          }
    
    then the HashMap after word "For"
    map = {
            {0, "GF"},
            {1, "eo"},
            {2, "er"},
            {3, "k$"},
            {4, "s$"}
          }
    
    then the HashMap after word "Geeks"
    map = {
            {0, "GFG"},
            {1, "eoe"},
            {2, "ere"},
            {3, "k$k"},
            {4, "s$s"}
          }
    
  5. The word at each index in the HashMap represents the word in the final vertical order traversal of the given string.
  6. Hence finally, the strings are taken (from each index) from the HashMap and are added to an array and the array is returned.
    For example:

    Vertial order traversal of the above example:
    "GFG eoe ere k$k s$s"
    

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the above approach.
  
import java.util.*;
  
class GFG {
  
    // Function to return the vertical order
    // traversal of String
    public static String printVertically(String s)
    {
        String result = "";
  
        // Hashmap to store the indices
        // of the characters
        HashMap<Integer, String> map
            = new HashMap<>();
  
        Scanner sc = new Scanner(s);
        int max = Integer.MIN_VALUE;
  
        // Finding maximum length word
        // from given string
        while (sc.hasNext()) {
            String st = sc.next();
            max = Math.max(max, st.length());
        }
  
        sc = new Scanner(s);
        while (sc.hasNext()) {
            String st = sc.next();
  
            // Inserting strings in the hashmap
            // in vertical fashion
            // based on character index
            for (int i = 0; i < st.length(); i++) {
                char ch = st.charAt(i);
                map.put(i, map.getOrDefault(i, "") + ch);
            }
  
            // If the string is smaller than the
            // maximum length string, then
            // add spaces in the string
            for (int i = st.length(); i < max; i++) {
                map.put(i,
                        map.getOrDefault(i,
                                         "")
                            + "$");
            }
        }
  
        // Adding  all String values in the list
        for (int i = 0; i < max; i++) {
            String a = map.get(i);
            result += a + " ";
        }
        return result;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String st = "ge ek sfor ge eks";
        System.out.println(printVertically(st));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the above approach.
  
# Function to return the vertical order
# traversal of
def printVertically(s):
    s = s.split(" ")
    result = ""
      
    # Hashmap to store the indices
    # of the characters
    map = dict()
    mx = 0
  
    # Finding maximum length word
    # from given string
    for i in s:
        mx = max(mx, len(i))
    n = mx
    i = 0
    while (i < mx):
          
        # Inserting strings in the hashmap
        # in vertical fashion
        # based on character index
        for j in s:
            if i >= len(j):
                map[i] = map.get(i, "") + "$"
            else:
                map[i] = map.get(i, "") + j[i]
        i += 1    
  
    # Adding all values in the list
    for j in range(mx):
        result += map[j] + " "
    return result
  
# Driver code
if __name__ == '__main__':
    st = "ge ek sfor ge eks"
    print(printVertically(st))
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach.
using System;
using System.Collections.Generic;
  
class GFG
{
  
    // Function to return the vertical order
    // traversal of String
    public static String printVertically(String s)
    {
        String result = "";
  
        // Hashmap to store the indices
        // of the characters
        Dictionary<int, String> map
            = new Dictionary<int, String>();
  
        String []sc = s.Split(' ');
        int max = int.MinValue;
        int i = 0;
          
        // Finding maximum length word
        // from given string
        while (i<sc.Length) 
        {
            String st = sc[i];
            max = Math.Max(max, st.Length);
            i++;
        }
  
        sc = s.Split(' ');
        i = 0;
        while (i < sc.Length) 
        {
            String st = sc[i];
  
            // Inserting strings in the hashmap
            // in vertical fashion
            // based on character index
            for (int j = 0; j < st.Length; j++)
            {
                char ch = st[j];
                if(map.ContainsKey(j))
                    map[j] = map[j] + ch;
                else
                    map.Add(j, ("") + ch);
            }
  
            // If the string is smaller than the
            // maximum length string, then
            // add spaces in the string
            for (int j = st.Length; j < max; j++)
            {
                if(map.ContainsKey(j))
                    map[j] = map[j] + "$";
                else
                    map.Add(j, ("") + "$");
            }
            i++;
        }
  
        // Adding all String values in the list
        for (int j = 0; j < max; j++)
        {
            String a = map[j];
            result += a + " ";
        }
        return result;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        String st = "ge ek sfor ge eks";
        Console.WriteLine(printVertically(st));
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

gesge ekfek $$o$s $$r$$

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.