767. Reorganize String

greedy

put most high freq first

ex: aaaaabbbbc

a_a_a_a_a_____

then put b into empty slot, then c

so the insert index is start at 0, but +=2,

if ( index > s.length), index = 1, to fill empty slot

fail case in Reorganize String

  1. if the highest freq is bigger than s.length/2, you cant complete the new String, return "";

  2. or just check if (i >= 1 && newStr[i] == newStr[i-1]), means cant reorganinze, return "";

time: O(n + klogk), n is String s length, k is the list<Pair> length

space: O(k), use map to keep freq, k is the kind of char, List<Pair> space is also O(k)

use array map

this is the fastest

T: O(n), n is s len

S: O(26 + n)

Last updated

Was this helpful?