-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathwordCompression.js
More file actions
45 lines (35 loc) · 1.09 KB
/
wordCompression.js
File metadata and controls
45 lines (35 loc) · 1.09 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
/*
Write a function `compressWords` which takes an array of strings as input and returns a new array with consecutive duplicate elements compressed. If an element appears consecutively, it is replaced by the element followed by the count of its occurrences.
Example:
- Input: ["apple", "apple", "banana", "banana", "banana", "cherry", "apple", "apple"]
- Output: ["apple2", "banana3", "cherry", "apple2"]
- Input: ["cat", "dog", "dog", "dog", "cat"]
- Output: ["cat", "dog3", "cat"]
- Input: ["one", "two", "three"]
- Output: ["one", "two", "three"]
- Input: []
- Output: []
Note:
- The function should handle empty arrays and arrays with no consecutive duplicates.
Once you've implemented the logic, test your code by running
- `npm run test-compressWord`
*/
function compressWords(arr) {
let n=arr.length;
let narr=[];
let cnt=0;
for(let i=0; i<n; i++){
cnt++;
if(arr[i]!==arr[i+1]){
if(cnt>1){
narr.push(arr[i]+cnt);
}
else{
narr.push(arr[i]);
}
cnt=0;
}
}
return narr;
}
module.exports = compressWords;