Python code to move spaces to front of string in single traversal
Last Updated :
23 Mar, 2023
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.
Approach 1:
- 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.
Implementation
Python3
# Function to move spaces to front of string
# in single traversal in Python
def moveSpaces(input):
# Traverse string to create string without spaces
noSpaces = [ch for ch in input if ch!=' ']
# calculate number of spaces
space= len(input) - len(noSpaces)
# create result string with spaces
result = ' '*space
# concatenate spaces with string having no spaces
result = '"'+result + ''.join(noSpaces)+'"'
print (result)
# Driver program
if __name__ == "__main__":
input = 'geeks for geeks'
moveSpaces(input)
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 2 : Using count() and replace() methods
Implementation
Python3
# Function to move spaces to front of string
# in single traversal in Python
def moveSpaces(input):
c=input.count(' ')
input=input.replace(' ','')
input=' '*c+input
print(input)
# Driver program
if __name__ == "__main__":
input = 'geeks for geeks'
moveSpaces(input)
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as the function creates a new string of length n (where n is the length of the input string) to store the modified string with spaces moved to the front.
Approach 3 : Using operator.countOf() and replace() methods
Python3
# Function to move spaces to front of string
# in single traversal in Python
def moveSpaces(input):
import operator
c=operator.countOf(input,' ')
input=input.replace(' ','')
input=' '*c+input
print(input)
# Driver program
if __name__ == "__main__":
input = 'geeks for geeks'
moveSpaces(input)
Time Complexity : O(N)
Auxiliary Space : O(1)
Approach 5: Using join() and split() methods
- Split the input string into a list of words using the split() method.
- Join the list of words using the join() method to form a new string without any space characters.
- Append the required number of space characters at the beginning of the modified string.
- Return the modified string.
Python3
def moveSpaces(input):
words = input.split()
modified_str = ''.join(words)
num_spaces = len(input) - len(modified_str)
modified_str = ' ' * num_spaces + modified_str
return modified_str
# Driver program
if __name__ == "__main__":
input_str = 'geeks for geeks'
print(moveSpaces(input_str))
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string (to store the list of words and the modified string).
Approach 6: Using regular expressions
Algorithm:
- The input string is passed to the function moveSpaces() as input_str.
- The re.sub() method is used to replace all occurrences of a space with an empty string in the input_str. The modified string is then stored in the variable modified_str.
- The number of spaces in the original input string is calculated by taking the difference between the length of input_str and the length of modified_str.
- The required number of spaces is added at the beginning of the modified string using the multiplication operator and the ' ' (space) character. The modified
- string is then stored back in the variable modified_str.
- The modified string is returned as the output of the function.
- Finally, the moveSpaces() function is called with the input string 'geeks for geeks' and the output is printed.
Python3
import re
def moveSpaces(input_str):
# Replace all occurrences of space with empty string
modified_str = re.sub(' ', '', input_str)
# Get the number of spaces in the original string
num_spaces = len(input_str) - len(modified_str)
# Add the required number of spaces at the beginning of the modified string
modified_str = ' ' * num_spaces + modified_str
return modified_str
input_str = 'geeks for geeks'
print(moveSpaces(input_str))
Time complexity: O(n), where n is the length of the input string. The regular expression re.sub() method used in this approach has a time complexity of O(n), where n is the length of the input string.
Space complexity: O(n), where n is the length of the input string. This is because the re.sub() method creates a new string with all spaces removed, which is stored in memory before being used to calculate the number of spaces in the original string and add the required number of spaces at the beginning of the modified string.
Similar Reads
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 = " movethesespacestobegin
6 min read
Regex in Python to put spaces between words starting with capital letters Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to
2 min read
How to Index and Slice Strings in Python? In Python, indexing and slicing are techniques used to access specific characters or parts of a string. Indexing means referring to an element of an iterable by its position whereas slicing is a feature that enables accessing parts of the sequence.Table of ContentIndexing Strings in PythonAccessing
2 min read
How to Substring a String in Python A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a str
4 min read
String containing first letter of every word in a given string with spaces String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space. Examples: Input : str = "geeks for geeks" Output : gfg Input : str = "geeks for geek
11 min read
Python - Remove empty strings from list of strings When working with lists of strings in Python, you may encounter empty strings (" ") that need to be removed. We'll explore various methods to Remove empty strings from a list. Using List ComprehensionList comprehension is the most concise and efficient method to filter out empty strings. This method
2 min read
Fill a Python String with Spaces This article will show you to fill out a python string with spaces to the left, right, and around a string in Python. Let's suppose we have a string GeeksforGeeks, and we want to fill N number of spaces on left, right, and around the string. Note that in the case of space around the string if N is o
3 min read
Python - Replace all occurrences of a substring in a string Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence
2 min read
Convert string to title case in Python In this article, we will see how to convert the string to a title case in Python. The str.title() method capitalizes the first letter of every word.Pythons = "geeks for geeks" result = s.title() print(result) OutputGeeks For Geeks Explanation:The s.title() method converts the string "python is fun"
2 min read
Python - Separate first word from String We need to write a Python program to split a given string into two parts at the KáµÊ° occurrence of a specified character. If the character occurs fewer than K times, return the entire string as the first part and an empty string as the second part. Separating the first word from a string involves ide
2 min read