Skip to content

Commit 150e9ee

Browse files
reduced string
1 parent 4ecf41a commit 150e9ee

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

FE-JS-Questions/ReduceString.md

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
> Given a string return a reduced string such that , the reduced string has the characters re-arranged
2+
3+
* in order of characters having highest frequencey
4+
* followed by character which appears just once in the same order as in the original string
5+
* and no duplicate characters
6+
7+
```
8+
Input: "hello world"
9+
Output: "lohe wrd"
10+
Explaination: 'l' appears thrice, 'o' appears twice, 'h','e', ' '(space) ,'w','r','d' all appear once
11+
'h','e',' ','w','r','d' should be appended in the same order as they appear in the original string hello world
12+
```
13+
14+
```js
15+
const reducedString = str => {
16+
const charMap = new Map();
17+
18+
for (let char of str.split('')) {
19+
charMap.has(char) ? charMap.set(char, charMap.get(char) + 1) : charMap.set(char, 1);
20+
}
21+
22+
return (
23+
[...charMap.entries()]
24+
.sort((a, b) => b[1] - a[1])
25+
.map(s => s[0])
26+
).join('');
27+
}
28+
```

exercises/arrays/summaryRanges.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Given a unsorted integer array without duplicates, return the summary of its ranges.
3+
4+
Example 1:
5+
6+
Input: [0,1,2,4,5,7]
7+
Output: ["0->2","4->5","7"]
8+
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
9+
Example 2:
10+
11+
Input: [0,2,3,4,6,8,9]
12+
Output: ["0","2->4","6","8->9"]
13+
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
14+
*/
15+
16+
const summaryRanges = nums => {
17+
if (nums.length === 0) {
18+
return [];
19+
}
20+
21+
nums.sort((a, b) => a - b);
22+
const result = [];
23+
24+
for (let start = 0, end = 0; end < nums.length; end++) {
25+
if (end + 1 < nums.length && nums[end + 1] === nums[end] + 1) {
26+
continue;
27+
}
28+
29+
if (start === end) {
30+
result.push(nums[start] + '');
31+
} else {
32+
result.push(start + '->' + end);
33+
}
34+
start = end + 1;
35+
}
36+
37+
return result;
38+
}

0 commit comments

Comments
 (0)