Given a string S and an integer N, the task is to remove N characters from the end of the string S.
Input: S = “GeeksForGeeks”, N = 5
Output: GeeksFor
Explanation: Removing the last 5 characters from “GeeksForGeeks” modifies the string to “GeeksFor”.Input: S = “Welcome”, N = 3
Output: Welc
Approach 1: Follow the steps below to solve the problem:
- Initialize an empty string, say res, to store the resultant string.
- Iterate over the characters of the string S up to index len(S) – N.
- Keep inserting the encountered characters into res.
Below is the implementation of the above approach:
Python3
# Python3 code for the above approach # Function to remove last N # characters from string def removeLastN(S, N): # Stores the resultant string res = '' # Traverse the string for i in range ( len (S) - N): # Insert current character res + = S[i] # Return the string return res # Driver Code # Input S = "GeeksForGeeks" N = 5 print (removeLastN(S, N)) |
GeeksFor
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(N)
Approach 2: This problem can be solved using replace(). Follow the steps below to solve the problem:
- Initialize a string, say res, to store the resultant string.
- Reverse the string S.
- Using replace() method, remove the first occurrence of the first N characters of S and store it in res.
- Reverse the string res.
Below is the implementation of the above approach:
Python3
# Python3 code for the above approach # Function to remove last N # characters from string S def removeLastN(S, N): # Stores resultant string res = '' # Reversing S S = S[:: - 1 ] # Removing last N characters res = S.replace(S[:N], '', 1 ) # Reversing back res res = res[:: - 1 ] # Return the string return res # Driver Code # Input S = "GeeksForGeeks" N = 5 print (removeLastN(S, N)) |
GeeksFor
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(N)
String slicing-based Approach: Follow the steps below to solve the problem:
- Initialize a string, say res, to store the resultant string.
- Update res to S[:len(S) – N], to store all characters except the last N characters of S.
Below is the implementation of the above approach:
Python3
# Python3 code for the above approach # Function to remove last N # characters from string S def removeLastN(S, N): S = S[: len (S) - N] # Return the string return S # Driver Code # Input S = "GeeksForGeeks" N = 5 print (removeLastN(S, N)) |
GeeksFor
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!