16. Valid Anagram
easyAsked at DatabricksDetermine whether two strings are anagrams — Databricks surfaces this in early screens to test whether you reach for a frequency map, the same mental model behind deduplication passes in Delta Lake compaction jobs.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given two strings s and t, return true if t is an anagram of s and false otherwise. An anagram uses all the original letters of s exactly once, rearranged.
Constraints
1 <= s.length, t.length <= 5 * 10^4s and t consist of lowercase English letters
Examples
Example 1
s = "anagram", t = "nagaram"trueExplanation: Both strings contain exactly one 'a','n','g','r','m','a' — same frequency profile.
Example 2
s = "rat", t = "car"falseApproaches
1. Brute force — sort and compare
Sort both strings and check equality. Simple but wastes O(n log n) on the sort.
- Time
- O(n log n)
- Space
- O(n)
function isAnagram(s, t) {
if (s.length !== t.length) return false;
return s.split('').sort().join('') === t.split('').sort().join('');
}Tradeoff:
2. Frequency map
Count character frequencies in s, decrement for t, then verify all counts are zero. Single pass, O(1) space over a fixed alphabet.
- Time
- O(n)
- Space
- O(1)
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const freq = new Array(26).fill(0);
const a = 'a'.charCodeAt(0);
for (let i = 0; i < s.length; i++) {
freq[s.charCodeAt(i) - a]++;
freq[t.charCodeAt(i) - a]--;
}
return freq.every(c => c === 0);
}Tradeoff:
Databricks-specific tips
Databricks interviewers want you to connect the frequency-map pattern to real data workloads — for instance, how a shuffle-hash join partitions records by key frequency. Call out O(1) space explicitly; they penalize candidates who accept O(n) without noticing the fixed-alphabet shortcut.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Valid Anagram and other Databricks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →