Frontend Interview Question: Most Frequent String in Array

🐵 One common frontend interview question: “Find the most frequently occurring string in an array.” Here’s a clean O(n) solution using reduce: Why this approach works well: ✔ Single pass to build frequency map ✔ Clean functional style ✔ Handles edge cases ✔ Linear time complexity As frontend engineers, we don’t just build UI — we solve data problems efficiently. What’s your favorite way to solve this? #JavaScript #Frontend #CodingInterview #WebDevelopment #SoftwareEngineering

  • const getMostCommonString = (strings) => {
  if (strings.length === 0) return null;

  const mapping = strings.reduce((acc, el) => {
    acc[el] = (acc[el] || 0) + 1;
    return acc;
  }, {});

  return Object.entries(mapping).reduce(
    (acc, el) => (el[1] > acc[1] ? el : acc),
    [null, 0]
  )[0];
};

You can do even better. Why iterate with reduce and then iterate with reduce again on the mapping? Do it all in the original reduce, in 1 iteration. Use part of the acc to store instances of a string in an internal store.

What about if the interviewer don’t allow you to use reduce?

See more comments

To view or add a comment, sign in

Explore content categories