A duplicate check needs to know whether a value has appeared. A permutation check needs to know how many times each value appears. The difference determines what I store while scanning the input.
Count first, then use the counts
Frequency counting has two phases. I first scan the input and record how often each value appears. I then use that record to answer the actual question, such as finding a duplicate or comparing two inputs.
Counts are useful for comparing two inputs or finding the most frequent value. When only existence matters, a membership flag can be enough.
Examples and storage choices
This duplicate check counts the values, then looks for a count above one:
function hasDuplicate(nums) {
const counts = {};
// Counting phase
for (let num of nums) {
counts[num] = (counts[num] || 0) + 1;
}
// Utilization phase
for (let num in counts) {
if (counts[num] > 1) {
return true; // Found a duplicate!
}
}
return false;
}
For permutations, count characters in the first string and subtract characters from the second:
function arePermutations(str1, str2) {
if (str1.length !== str2.length) return false;
const counts = {};
// Count characters in first string
for (let char of str1) {
counts[char] = (counts[char] || 0) + 1;
}
// Decrement for second string
for (let char of str2) {
if (!counts[char]) return false;
counts[char]--;
}
// All should be zero if they're permutations
return Object.values(counts).every((count) => count === 0);
}
A hash map is the common choice. I use each element as a key and its frequency as the value:
const frequency = {};
for (let item of data) {
frequency[item] = (frequency[item] || 0) + 1;
}
When the values are small integers, an array can use the value as an index:
const frequency = new Array(26).fill(0); // For lowercase letters
for (let char of str) {
frequency[char.charCodeAt(0) - "a".charCodeAt(0)]++;
}
Complexity and checklist
The counting pass takes O(n) time, followed by a scan of the distinct values. A hash map uses O(k) space for k distinct values. A fixed array reserves space for the whole chosen range.
I choose the state from the question the next step needs to answer. Storing counts when only membership matters works, but it keeps more information than the algorithm needs.

Loading comments...