VOOZH about

URL: https://www.geeksforgeeks.org/dsa/create-new-string-alternately-combining-characters-two-halves-string-reverse/

⇱ Create a new string by alternately combining the characters of two halves of the string in reverse - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create a new string by alternately combining the characters of two halves of the string in reverse

Last Updated : 8 Mar, 2023

Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. 

Examples: 

Input : s = carbohydrates
Output : hsoebtraarcdy

Input : s = sunshine
Output : sennuish

Explanation: 

Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be added in reverse alternately, start with h from first half then s from second half followed by o from first half, e from second half and so on. The string p comes out to be hsoebtraarcdy. If one of the string is completely finished then simply add the remaining characters of the other string in reverse order. 

Example 2: The two halves of the string are suns and hine. String sennuish is the desired string p.

Algorithm:

  • Define a method named "solve" of void return type which takes string "s" as an input parameter.
  •  Create three int variables named "l", "x", and "y" and initialize them with a length of the string, half the length of the string,              and the length of the string respectively.
  • Define an empty string variable "p" to store the final output string.
  •  Start a while loop, and iterate until variable "x" is greater than 0 and variable "y" is greater than l/2.
    • get the character at index (x-1) and add it to string "p". Then, decrement the value of "x".
    •  Again, get the character at index (y-1) and add it to string "p". Then, decrement the value of "y".
  •  If "y" is greater than l/2, then get the character at index (y-1) and add it to string "p".
  •  Then, decrement the value of "y".
  • Finally, print the string "p".
     

Implementation:


Output
sennuish

Time complexity: O(n) where n is the length of the string
Auxiliary Space: O(n)

Comment
Article Tags: