Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples:
Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, all of them should be shifted in front.
This problem has existing solution, please refer Move spaces to front of string in single traversal link. We will solve this problem quickly in Python using List Comprehension.
- Traverse input string and create a string without any space character using list comprehension.
- Now to know how many space characters were there in original string just take a difference of length of original string and new string.
- Now create another string and append space characters at the beginning.
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 2 : Using count() and replace() method