Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to move spaces to front of string in single traversal
Given a string that has set of words and spaces, our task is to move all spaces to front of string, by traversing the string only once. We will solve this problem quickly in Python using list comprehension.
Example
Input: string = "python program" Output: string = " pythonprogram"
Algorithm
The algorithm follows these steps:
- Input a string with words and spaces
- Traverse the input string using list comprehension to extract non-space characters
- Calculate the number of spaces in the original string
- Create a result string with all spaces at the front
- Concatenate the non-space characters to the spaces
- Display the final string
Implementation
def move_spaces_to_front(input_string):
# Extract non-space characters using list comprehension
non_space_chars = [char for char in input_string if char != ' ']
# Calculate number of spaces
space_count = len(input_string) - len(non_space_chars)
# Create result with spaces at front
result = ' ' * space_count + ''.join(non_space_chars)
return result
# Test the function
test_string = "python program"
result = move_spaces_to_front(test_string)
print(f"Input: '{test_string}'")
print(f"Output: '{result}'")
Input: 'python program' Output: ' pythonprogram'
Example with Multiple Spaces
# Testing with multiple spaces
test_cases = [
"hello world",
"a b c d",
"python programming",
" spaces everywhere "
]
for test in test_cases:
result = move_spaces_to_front(test)
print(f"'{test}' ? '{result}'")
'hello world' ? ' helloworld' 'a b c d' ? ' abcd' 'python programming' ? ' pythonprogramming' ' spaces everywhere ' ? ' spaceseverywhere'
How It Works
The solution uses a single traversal approach:
-
List Comprehension:
[char for char in input_string if char != ' ']extracts all non-space characters in one pass - Space Counting: Calculates spaces by subtracting the length of non-space characters from original string length
- String Construction: Uses string multiplication to create the required number of spaces, then joins the non-space characters
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Single traversal of the string |
| Space | O(n) | Additional space for storing non-space characters |
Conclusion
This approach efficiently moves all spaces to the front of a string using list comprehension and string operations. The single traversal ensures optimal time complexity while maintaining code readability.
Advertisements
