Reverse Words in a String

How to reverse words in a String?

In this problem, we have given an input string, we have to write a code to reverse the string word by word.

Example 1:

Input : “the carpet is green”

Output: “green is carpet the”

Example 2:

Input : ”  Java Ebook  “

Output: “Ebook Java”

Explanation: The reversed string should not contain leading or trailing spaces.

Example 3:

Input : “a good   example”

Output: “example good a”

Explanation: We have reduce multiple spaces between two words to a single space in the reversed string.

Note:

  • The Input string may contain leading or trailing spaces. However, the reversed string should not contain leading or trailing spaces.
  • We have to reduce multiple spaces between two words to a single space in the reversed string.

Sort a Stack using Recursion

In this problem, We have to write a code to sort a stack using recursion. We have to sort in a descending order (Top of the stack has the greatest element).

We don’t have to use any loop constructs ( for, while etc) or additional data structure.

For Example –

In this example, You can see after sorting the stack, the element which has greater value is at the top of the stack.

Sort a stack using recursion

Find Nth Ugly Number

Given a number N, we have to write a code to find the Nth ugly number.

What is Ugly Numbers?

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. In simple words, The number which can be represented as the product of 2, 3 and 5 are ugly numbers (2^i * 3^i * 5^i).

For Example –

Input : n = 10, Output : 12

12 is the 10th ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.

Note:  

1 is typically treated as an ugly number.

n does not exceed 1690.