Write a program that transforms the user input stream: (1st) A B C A B C A B C (last) into the output (1st) C B A B A C C B A . The challenge increases when you use fewer variables. (program also solves: In: ????????? → Out: ?????????) Important: Use as little memory as possible to solve this problem. It can be solved with as few as 1 declared variable, but you may take an easier path.
Write a
output (1st) C B A B A C C B A . The challenge increases when you use fewer variables.
(program also solves: In: ????????? → Out: ?????????)
Important: Use as little memory as possible to solve this problem. It can be solved with as few
as 1 declared variable, but you may take an easier path.
Here our task is to transform user input to the given format.
User input will be a string, if we are implementing this program in python, java etc we require more memory as strings are immutable in them.
In programming languages like C, C++ strings could be declared as character array and it is mutable. Hence we are able make changes in the input string itself. Thus, we can able to acquire this task in O(1) space complexity.
Since the programming language is not specified here and our task is to ensure minimal usage of memory, I am choosing C++ here.
We can use a single variable temp inorder to perform the swap operation here and change its value at each swap, so that we can save memory.
Trending now
This is a popular solution!
Step by step
Solved in 4 steps with 2 images