Skip to content

Commit c8ade32

Browse files
committed
Add reverse words in string problem
1 parent a91c636 commit c8ade32

File tree

5 files changed

+100
-30
lines changed

5 files changed

+100
-30
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ List of Programs related to data structures and algorithms
100100

101101
10. Greatest common devisor of strings: [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/strings/10.greatestCommonDivisor/greatestCommonDivisor.js) [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/strings/10.greatestCommonDivisor/greatestCommonDivisor.js) [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/strings/10.greatestCommonDivisor/greatestCommonDivisor.md)
102102

103+
11. Reverse words in string: [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/strings/11.reverseWordsInString/reverseWordsInString.js) [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/strings/11.reverseWordsInString/reverseWordsInString.js) [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/strings/11.reverseWordsInString/reverseWordsInString.md)
104+
103105
### Dynamic programming
104106

105107
1. Climbing stairs: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/dynamicProgramming/climbingStairs.js)

src/java1/algorithms/strings/reverseWordsInString/ReverseWordsInString.java

+17-14
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,6 @@ public class ReverseWordsInString {
44

55
// TC: O(n) SC: O(n)
66
private static String reverseWordsInString1(String str) {
7-
String[] arr = str.split("\\s+");
8-
9-
String res = "";
10-
for (int i = arr.length - 1; i >= 0; i--) {
11-
res += arr[i] + " ";
12-
}
13-
14-
return res.substring(0, res.length() - 1);
15-
}
16-
17-
// TC: O(n) SC: O(1)
18-
private static String reverseWordsInString2(String str) {
197
String[] words = str.split("\\s+");
208
int i = 0, j = words.length - 1;
219

@@ -29,9 +17,24 @@ private static String reverseWordsInString2(String str) {
2917
return String.join(" ", words);
3018
}
3119

20+
// TC: O(n) SC: O(n)
21+
private static String reverseWordsInString2(String str) {
22+
String[] arr = str.split("\\s+");
23+
24+
String res = "";
25+
for (int i = arr.length - 1; i >= 0; i--) {
26+
res += arr[i];
27+
if(i != 0){
28+
res += " ";
29+
}
30+
}
31+
32+
return res.substring(0, res.length());
33+
}
34+
3235
public static void main(String[] args) {
33-
String str1 = "the sky is blue";
34-
String str2 = " hello world ";
36+
String str1 = "It is fun to learn DSA";
37+
String str2 = " hello DSA ";
3538
System.out.println(reverseWordsInString1(str1));
3639
System.out.println(reverseWordsInString1(str2));
3740

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
**Description:**
2+
Given an input string `str`, Return a string of the words in reverse order concatenated by a single space without having extra spaces.
3+
4+
### Examples
5+
Example 1:
6+
Input: "It is fun to learn DSA"
7+
Output: "DSA learn to fun is It"
8+
9+
Example 2:
10+
Input: "hello DSA"
11+
Output: "DSA hello"
12+
13+
**Algorithmic Steps**
14+
This problem is solved with the help of basic string and array operations. The algorithmic approach can be summarized as follows:
15+
16+
1. Split the input sentence `str` into array of words based on a space separator(one or more spaces). Store the result into `words` variable.
17+
18+
2. Initialize two pointers (`left` and `right`) pointing to the beginning and ending index of the sentence.
19+
20+
3. Iterate over the input sentence until left pointer is less than or equal to right pointer.
21+
22+
4. Swap the words indexed with left and right pointers.
23+
24+
5. Shrink the window by incrementing left pointer and decrementing the right pointer.
25+
26+
6. Repeat steps 4-5 until the iteration condition failed.
27+
28+
7. Join the reversed words with a space delimitor and return the result.
29+
30+
**Time and Space complexity:**
31+
This algorithm has a time complexity of `O(n)` where `n` is the length of first string. This is because we need to traverse the string at once for spliting the string based on a space, reversing the string, and joining the words back to a string. All these operations requires `O(n)`. Since all these operations performed sequentially, the overall time complexity combining these operations doesn't exceed `O(n)`.
32+
33+
Also, it takes space complexity of `O(n)` due to storing all the characters in an array.

src/javascript/algorithms/strings/reverseWordsInString/reverseWordsInString.js

+15-16
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,30 @@
11
//TC: O(n) SC: O(n)
22
function reverseWordsInString1(str) {
3-
let words = str.trim().split("/s+/");
4-
let result = "";
3+
let words = str.trim().split(/\s+/);
4+
let i = 0, j = words.length - 1;
55

6-
for (let i = words.length - 1; i >= 0; i--) {
7-
result += words[i] + " ";
6+
while (i <= j) {
7+
[words[i], words[j]] = [words[j], words[i]];
8+
i++;
9+
j--;
810
}
9-
10-
return result.slice(0, result.length - 1);
11+
return words.join(' ');
1112
}
1213

13-
//TC: O(n) SC: O(1)
14+
//TC: O(n) SC: O(n)
1415
function reverseWordsInString2(str) {
15-
let words = str.trim().split("/\s+/");
16-
let i = 0, j = str.length - 1;
16+
let words = str.trim().split(/\s+/);
17+
let result = "";
1718

18-
while (i <= j) {
19-
[words[i], words[j]] = [words[j], words[i]];
20-
i++;
21-
j--;
19+
for (let i = words.length - 1; i >= 0; i--) {
20+
result += words[i] + " ";
2221
}
2322

24-
return words.join("");
23+
return result.slice(0, result.length - 1);
2524
}
2625

27-
let str1 = "the sky is blue";
28-
let str2 = " hello world ";
26+
let str1 = "It is fun to learn DSA";
27+
let str2 = " hello DSA ";
2928
console.log(reverseWordsInString1(str1));
3029
console.log(reverseWordsInString1(str2));
3130

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
**Description:**
2+
Given an input string `str`, Return a string of the words in reverse order concatenated by a single space without having extra spaces.
3+
4+
### Examples
5+
Example 1:
6+
Input: "It is fun to learn DSA"
7+
Output: "DSA learn to fun is It"
8+
9+
Example 2:
10+
Input: "hello DSA"
11+
Output: "DSA hello"
12+
13+
**Algorithmic Steps**
14+
This problem is solved with the help of basic string and array operations. The algorithmic approach can be summarized as follows:
15+
16+
1. Split the input sentence `str` into array of words based on a space separator(one or more spaces). Store the result into `words` variable.
17+
18+
2. Initialize two pointers (`left` and `right`) pointing to the beginning and ending index of the sentence.
19+
20+
3. Iterate over the input sentence until left pointer is less than or equal to right pointer.
21+
22+
4. Swap the words indexed with left and right pointers.
23+
24+
5. Shrink the window by incrementing left pointer and decrementing the right pointer.
25+
26+
6. Repeat steps 4-5 until the iteration condition failed.
27+
28+
7. Join the reversed words with a space delimitor and return the result.
29+
30+
**Time and Space complexity:**
31+
This algorithm has a time complexity of `O(n)` where `n` is the length of first string. This is because we need to traverse the string at once for spliting the string based on a space, reversing the string, and joining the words back to a string. All these operations requires `O(n)`. Since all these operations performed sequentially, the overall time complexity combining these operations doesn't exceed `O(n)`.
32+
33+
Also, it takes space complexity of `O(n)` due to storing all the characters in an array.

0 commit comments

Comments
 (0)