#️⃣ PHP Hashing Basics

PHP Arrays as Hash Maps

PHP arrays double as both ordered arrays and hash maps (associative arrays).

// String keys — hash map
$map = [];
$map['apple'] = 3;
$map['banana'] = 5;
echo $map['apple']; // 3
isset($map['cherry']); // false

// Integer keys — can still use as hash map
$freq = [];
$nums = [1, 2, 2, 3, 1];
foreach ($nums as $n) $freq[$n] = ($freq[$n] ?? 0) + 1;
// $freq = [1=>2, 2=>2, 3=>1]

Hash Set (Uniqueness Check)

PHP has no built-in Set, but you can use array keys:

$seen = [];
$nums = [1, 2, 2, 3, 4, 1];
$unique = [];
foreach ($nums as $n) {
    if (!isset($seen[$n])) { $seen[$n] = true; $unique[] = $n; }
}
// $unique = [1, 2, 3, 4]

// Or simply:
$unique = array_unique($nums);

// Check membership O(1):
if (isset($seen[42])) { /* exists */ }

Frequency Counting

// Character frequency
function charFreq(string $s): array {
    $freq = [];
    for ($i = 0; $i < strlen($s); $i++) $freq[$s[$i]] = ($freq[$s[$i]] ?? 0) + 1;
    return $freq;
}

// Word frequency
$words = ['hello', 'world', 'hello', 'php'];
$freq  = array_count_values($words);
// ['hello' => 2, 'world' => 1, 'php' => 1]

Two-Sum Pattern

function twoSum(array $nums, int $target): array {
    $map = [];
    foreach ($nums as $i => $n) {
        $comp = $target - $n;
        if (isset($map[$comp])) return [$map[$comp], $i];
        $map[$n] = $i;
    }
    return [];
}

Prefix Sum with Hash Map

function subarraySum(array $nums, int $k): int {
    $prefixCount = [0 => 1]; // sum → count of occurrences
    $sum = 0; $result = 0;
    foreach ($nums as $n) {
        $sum += $n;
        $result += ($prefixCount[$sum - $k] ?? 0);
        $prefixCount[$sum] = ($prefixCount[$sum] ?? 0) + 1;
    }
    return $result;
}

Common PHP Hash Functions

FunctionPurpose
isset($arr[$key])O(1) key existence check
array_key_exists($key, $arr)O(1) — also works for null values
array_flip($arr)Swap keys and values (values become keys)
array_count_values($arr)Count occurrences
array_unique($arr)Remove duplicates

Complexity Summary

OperationAverageWorst
InsertO(1)O(n)
LookupO(1)O(n)
DeleteO(1)O(n)
SpaceO(n)O(n)

Worst case occurs due to hash collisions (rare with PHP's implementation).