Data Structures & AlgorithmsHardCodeforces Div2 B · DP warm-up

Problem: Which statement about the time complexity of checking if two strings are anagrams is most efficient and correct?

  1. A. O(n log n) is the best possible, via sorting
  2. B. O(1), since anagram checks don't depend on string length
  3. C. O(n) using a character frequency count (array or hash map of size equal to the alphabet), avoiding the O(n log n) cost of sorting both strings
  4. D. O(n^2), comparing every pair of characters

Correct answer: C. O(n) using a character frequency count (array or hash map of size equal to the alphabet), avoiding the O(n log n) cost of sorting both strings

Counting character frequencies in both strings (O(n) total) and comparing the counts is strictly faster than sorting both strings (O(n log n)) for determining whether they are anagrams.

More Coding Interview Problems questions

Exams that ask this topic