![]() |
VOOZH | about |
Given an Integer list, perform join with the delimiter, avoiding the extra delimiter at the end.
Input : test_list = [4, 7, 8, 3, 2, 1, 9], delim = "*"
Output : 4*7*8*3*2*1*9
Explanation : The rear "*" which usually occurs in concatenation, is avoided.
Input : test_list = [4, 7, 8, 3], delim = "*"
Output : 4*7*8*3
Explanation : The rear "*" which usually occurs in concatenation, is avoided.
Method #1: Using String slicing
Use string slice to slice off the last character from the string after forming.
Step by step approach :
Below is the implementation of the above approach:
The original list is : [4, 7, 8, 3, 2, 1, 9] The joined string : 4$7$8$3$2$1$9
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Method #2 : Using map() + join() + str()
In this, we completely avoid loop method to solve this problem, and employ map() to convert to string and join() to perform task of join.
The original list is : [4, 7, 8, 3, 2, 1, 9] The joined string : 4$7$8$3$2$1$9
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using str.join() with list comprehension
We can use a list comprehension to convert each element of the list to a string and then use the str.join() method to join the elements with the delimiter. Finally, we can remove the last occurrence of the delimiter using string slicing.
The original list is : [4, 7, 8, 3, 2, 1, 9] The joined string : 4$7$8$3$2$1$
Time complexity: The time complexity of the given program is O(n), where n is the length of the input list.
Auxiliary space: The auxiliary space used by the program is O(n), where n is the length of the input list.
Method #4: Using reduce() and lambda function:
Step-by-Step Approach:
The Original List is : [4, 7, 8, 3, 2, 1, 9] The joined string : 4$7$8$3$2$1$9
Time Complexity: O(n), where n is the length of the input list
This is because in this case, the lambda function is applied to the entire list in a sequential manner.
Space Complexity: O(n), where n is the length of the input list
This is because the reduce() function requires additional memory to store intermediate results.
Method #5: Using str.rstrip()
This program is designed to remove the last occurrence of a delimiter from a list of integers and join them using the delimiter.
The original list is : [4, 7, 8, 3, 2, 1, 9] The joined string : 4$7$8$3$2$1$9
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), where n is the length of the list, for storing the joined string.
Method 5: Using a loop and string concatenation
Step-by-step approach:
Below is the implementation of the above approach:
The original list is : [4, 7, 8, 3, 2, 1, 9] The joined string : 4$7$8$3$2$1$9
Time complexity: O(n)
Auxiliary space: O(n)