Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
The solution is elegant but hard to understand. The tiny change to the solution ...

Viacheslav Lushchinskiy

Nov 3, 2022

The solution is elegant but hard to understand. The tiny change to the solution could make it easier to comprehend. Maybe less efficient but probably with the same O(N)

My algorithm :

  • keep track of the sum of all characters in the frequency hashmap
  • on each iteration extract the value of the max repeating character in that hashmap
  • if the remaining sum is more than K, shrink the window.

The hole solution in JS: const f = (_str, _k) => { let windowStart = 0; let maxLength = 0; const charFrequency = {}; let allCharSum = 0;

for (let windowEnd = 0; windowEnd < _str.length; windowEnd++) { const rightChar = _str[windowEnd];

if (!(rightChar in charFrequency)) { charFrequency[rightChar] = 0; } charFrequency[rightChar] += 1; allCharSum += 1;

// Find the max value and delete it from the overall sum. // The sum of the other values should not be more than K const otherCharSum = allCharSum - Math.max(...Object.values(charFrequency));

if (otherCharSum > _k) { const leftChar = _str[windowStart]; charFrequency[leftChar] -= 1; allCharSum -= 1; windowStart += 1; } maxLength = Math.max(maxLength, windowEnd - windowStart + 1); } return maxLength; };

4

0

Comments
Comments
Nikhil Jain
Nikhil Jaina year ago

I don't think this is O(n) anymore. Specially in the worst case scenario.

On this page