GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #767 - Reorganize String - LeetCode JavaScript Solutions

Back to all solutions

#767 - Reorganize String

Medium • View on LeetCode • View on GitHub
String Hash Table Sorting Greedy Heap Priority Queue Counting

Problem Description

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of s or return "" if not possible.

Solution

/**
 * @param {string} s
 * @return {string}
 */
var reorganizeString = function(s) {
  const charCount = new Map();
  for (const char of s) {
    charCount.set(char, (charCount.get(char) || 0) + 1);
  }

  const maxHeap = [...charCount.entries()]
    .sort((a, b) => b[1] - a[1]);

  if (maxHeap[0][1] > Math.ceil(s.length / 2)) {
    return '';
  }

  const result = [];
  let index = 0;

  while (maxHeap.length) {
    const [char, count] = maxHeap.shift();
    for (let i = 0; i < count; i++) {
      result[index] = char;
      index += 2;
      if (index >= s.length) index = 1;
    }
  }

  return result.join('');
};
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.