-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunnyString.ts
More file actions
71 lines (57 loc) · 2.45 KB
/
Copy pathfunnyString.ts
File metadata and controls
71 lines (57 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
In this challenge, you will determine whether a string is funny or not. To determine whether a string is funny, create a copy of the string in reverse e.g. .
Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end.
If the list of absolute differences is the same for both strings, they are funny.
Determine whether a give string is funny. If it is, return Funny, otherwise return Not Funny.
s = 'lmnop'
The ordinal values of the charcters are [108, 109, 110, 111, 112]. s' = 'ponml' and the ordinals are [112, 111, 110, 109, 108].
The absolute differences of the adjacent elements for both strings are [1, 1, 1, 1], so the answer is Funny.
Sample Input
STDIN Function
----- --------
2 q = 2
acxz s = 'acxz'
bcxz s = 'bcxz'
Sample Output
Funny
Not Funny
*/
// First, we will create a list to save the absolute different of adjacent elements for the original string
// Ex: [108, 109, 110, 111, 112]
// After that, we will run a for loop to the haft of the list and compare follow the rule
// If all of the values has l[i] === l[length of list - i] => It is funny string
// Otherwise, it is not a funny string
function funnyString(s: string) {
// Approach 1: Time: O(n), Space: O(n)
// const differenceList = [];
// for (let i = 0; i < s.length - 1; i++) {
// differenceList.push(Math.abs(s.charCodeAt(i + 1) - s.charCodeAt(i)));
// }
// for (let i = 0; i < differenceList.length / 2; i++) {
// if (differenceList[i] !== differenceList[differenceList.length - i - 1]) {
// return 'Not Funny';
// }
// }
// return 'Funny';
// Approach 2: Time O(n), Space: O(1)
// In this approach, we will need 2 pointer
// The first pointer (left) for the loop from the index 0 to s.length / 2
// The second pointer (right) for the loop from the index s.length - 2 to s.length / 2
// We will use the while loop, with condition is left <= right
// And compare the absolute of the different of the adjacent elements between the haft left and haft right
let left = 0;
let right = s.length - 2;
let leftDifferent: number;
let rightDifferent: number;
while (left <= right) {
leftDifferent = Math.abs(s.charCodeAt(left) - s.charCodeAt(left + 1));
rightDifferent = Math.abs(s.charCodeAt(right) - s.charCodeAt(right + 1));
if (leftDifferent !== rightDifferent) {
return 'Not Funny';
}
left++;
right--;
}
return 'Funny';
}
console.log(funnyString('bcxz'));