AI Hints
Home›JavaScript Tutorial›Interview Questions
JavaScript · Lesson 130 of 138

Interview Questions 1

Strings and arrays.

⏱ 2 min read▶ Video at 2:35:58🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

JavaScript interviews often start with small problems about strings and arrays. They're not tricky on purpose. They check that you know the built in methods, and can explain your thinking. Let's solve three classics.

Interview Questions 1
From the video: Interview Questions 1
  • Strings and arrays first
  • Know the methods
  • Explain your thinking

Palindrome, anagram, and max

A palindrome reads the same backwards. We clean the text, keeping only letters and digits, then compare it with its reverse. Two words are anagrams if their sorted letters match. And the largest number is just math dot max, with the array spread into it. Run it.

app.jsjavascript
const clean = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
const isPalindrome = (s) => clean(s) === [...clean(s)].reverse().join("");

const sortLetters = (s) => [...clean(s)].sort().join("");
const isAnagram = (a, b) => sortLetters(a) === sortLetters(b);

console.log(isPalindrome("A man, a plan, a canal: Panama"), isPalindrome("hello"));
console.log(isAnagram("listen", "silent"), isAnagram("cat", "car"));
console.log(Math.max(...[4, 19, 7, 12]));
Output
true false
true false
19

Count characters

Another favourite. Find the most common character in a string. We count each character in a map, then pick the entry with the highest count using reduce. This shows you can combine a map, a loop, and reduce. Run it.

app.jsjavascript
function mostCommon(text) {
  const counts = new Map();
  for (const ch of text.replaceAll(" ", "")) {
    counts.set(ch, (counts.get(ch) ?? 0) + 1);
  }
  return [...counts].reduce((best, cur) => (cur[1] > best[1] ? cur : best));
}

console.log(mostCommon("hello world"));
console.log(mostCommon("javascript is fun"));
Output
[ 'l', 3 ]
[ 'a', 2 ]

Summary

Clean the input, then use reverse, sort, spread, and maps. Say out loud what each step does. Next, questions about how JavaScript itself behaves.

Key takeaways
  • Clean, then compare
  • Sort letters for anagrams
  • Count with a Map
Next up: Interview Questions 2 — scope, this, and closures