Skip to content

Commit 986b593

Browse files
authored
avc278 - 1.09 - Javascript (#64)
Added my solution to the Chapter 1 Problem 9 folder. This is the final problem in chapter 1 tada
1 parent 9fd697d commit 986b593

File tree

1 file changed

+35
-0
lines changed
  • JavaScript/chapter01/p09_string_rotation

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// String Rotation: Assume you have a method `isSubstring` which checks if one word is a substring of another. Given two
2+
// strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to `isSubstring`.
3+
4+
const assert = require("assert");
5+
6+
/**
7+
* Checks if one string is a rotation of another string
8+
* @param {string} s1 input string to check against
9+
* @param {string} s2 input string to check if is a rotation of s1
10+
* @return {boolean} whether s2 is a rotation of s1
11+
*
12+
* We can use the built-in method String.prototype.includes() to solve the problem for us,
13+
* checking if s1s1 of size 2N, where N is the length of s1, contains the string s2, also of size N at this point.
14+
*
15+
* Runtime: O(N)
16+
* Space: O(1)
17+
*
18+
*/
19+
const isSubstring = (s1, s2) => {
20+
if (s1.length !== s2.length) return false;
21+
return `${s1}${s1}`.includes(s2);
22+
};
23+
24+
describe(module.filename, () => {
25+
it("should return false when both input strings are not of the same length", () => {
26+
const s1 = "hi";
27+
const s2 = "hello";
28+
assert.ok(!isSubstring(s1, s2));
29+
});
30+
it("should return true when s2 is a valid rotation of s1", () => {
31+
const s1 = "waterbottle";
32+
const s2 = "erbottlewat";
33+
assert.ok(isSubstring(s1, s2));
34+
});
35+
});

0 commit comments

Comments
 (0)