Problem solution · C++

Longest Balanced Substring II

Longest Balanced Substring II: a C++ solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Hash-based lookup
Source
Kamyu LeetCode Solutions
Length
79 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Hash-based lookup

For Longest Balanced Substring II, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 79 lines of C++ from the credited upstream file longest-balanced-substring-ii.cpp.
  • The implementation visibly relies on hash lookup.
  • 3 loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeLongest Balanced Substring II · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n)// Space: O(n) // hash table, prefix sumclass Solution {private:    template <typename T>    struct PairHash {        size_t operator()(const pair<T, T>& p) const {            size_t seed = 0;            seed ^= std::hash<T>{}(p.first)  + 0x9e3779b9 + (seed<<6) + (seed>>2);            seed ^= std::hash<T>{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);            return seed;        }    }; public:    int longestBalanced(string s) {        const auto& count1 = [&]() {            int result = 0, cnt = 0;            for (int i = 0; i < size(s); ++i) {                ++cnt;                if (i + 1 == size(s) || s[i + 1] != s[i]) {                    result = max(result, cnt);                    cnt = 0;                }            }            return result;        };         const auto& count2 = [&](auto a, auto b) {            int result = 0, cnt = 0;            unordered_map<int, int> lookup = {{cnt, -1}};            for (int i = 0; i < size(s); ++i) {                if (s[i] == a) {                    ++cnt;                } else if (s[i] == b) {                    --cnt;                } else {                    cnt = 0;                    lookup = {{cnt, i}};                    continue;                }                if (lookup.count(cnt)) {                    result = max(result, i - lookup[cnt]);                } else {                    lookup[cnt] = i;                }            }            return result;        };            const auto& count3 = [&]() {            int result = 0, a = 0, b = 0;            unordered_map<pair<int, int>, int, PairHash<int>> lookup = {{{a, b}, -1}};            for (int i = 0; i < size(s); ++i) {                if (s[i] == 'a') {                    ++a;                } else if (s[i] == 'b') {                    ++b;                } else {                    --a;                    --b;                }                if (lookup.count({a, b})) {                    result = max(result, i - lookup[{a, b}]);                } else {                    lookup[{a, b}] = i;                }            }            return result;        };                return max({count1(),                     count2('a', 'b'), count2('b', 'c'), count2('c', 'a'),                    count3()});    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗