Skip to content

Commit c4c745a

Browse files
committed
Add solution #761
1 parent c2e0924 commit c4c745a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,7 @@
575575
754|[Reach a Number](./0754-reach-a-number.js)|Medium|
576576
756|[Pyramid Transition Matrix](./0756-pyramid-transition-matrix.js)|Medium|
577577
757|[Set Intersection Size At Least Two](./0757-set-intersection-size-at-least-two.js)|Hard|
578+
761|[Special Binary String](./0761-special-binary-string.js)|Hard|
578579
762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
579580
763|[Partition Labels](./0763-partition-labels.js)|Medium|
580581
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 761. Special Binary String
3+
* https://leetcode.com/problems/special-binary-string/
4+
* Difficulty: Hard
5+
*
6+
* Special binary strings are binary strings with the following two properties:
7+
* - The number of 0's is equal to the number of 1's.
8+
* - Every prefix of the binary string has at least as many 1's as 0's.
9+
*
10+
* You are given a special binary string s.
11+
*
12+
* A move consists of choosing two consecutive, non-empty, special substrings of s,
13+
* and swapping them. Two strings are consecutive if the last character of the first
14+
* string is exactly one index before the first character of the second string.
15+
*
16+
* Return the lexicographically largest resulting string possible after applying
17+
* the mentioned operations on the string.
18+
*/
19+
20+
/**
21+
* @param {string} s
22+
* @return {string}
23+
*/
24+
function makeLargestSpecial(s) {
25+
if (s.length <= 2) return s;
26+
27+
let count = 0;
28+
let start = 0;
29+
const specials = [];
30+
31+
for (let i = 0; i < s.length; i++) {
32+
count += s[i] === '1' ? 1 : -1;
33+
34+
if (count === 0) {
35+
specials.push('1' + makeLargestSpecial(s.slice(start + 1, i)) + '0');
36+
start = i + 1;
37+
}
38+
}
39+
40+
return specials.sort().reverse().join('');
41+
}

0 commit comments

Comments
 (0)