Code Logo

Key-Value with Map<string, number>

Published at25 Jul 2026
TypeScript Collections Easy 0 views
Like0

Write a TypeScript function that takes a string and returns a Map where each character is mapped to its frequency. The Map generic type ensures keys are strings and values are numbers at compile time.

TypeScript's Map is a typed version of JavaScript's Map. K is the key type and V is the value type. Using Map ensures that only strings can be used as keys and only numbers as values. The compiler catches type mismatches during development.

Maps have several advantages over plain objects for dictionaries: they preserve insertion order, accept any type as key (not just strings), have a .size property, and provide .has(), .get(), .set(), .delete() methods. TypeScript's generics make all these operations type-safe.

Time complexity is O(n) where n is the string length. Each Map operation is O(1) average. Space complexity is O(k) where k is the number of unique characters.

Edge cases include empty strings (return empty Map), strings with all same characters, and ensuring the Map's get() method returns V | undefined which requires undefined checks.

Example Input & Output

Example 1
Input
"aaaa"
Output
{"a":4}
Explanation

Same char

Example 2
Input
"hello"
Output
{"h":1,"e":1,"l":2,"o":1}
Explanation

Character frequencies

Example 3
Input
""
Output
{}
Explanation

Empty string

Example 4
Input
"aab"
Output
{"a":2,"b":1}
Explanation

Two a's

Example 5
Input
"xyz"
Output
{"x":1,"y":1,"z":1}
Explanation

All unique

Algorithm Flow

Recommendation Algorithm Flow for Key-Value with Map<string, number>
Recommendation Algorithm Flow for Key-Value with Map<string, number>

Solution Approach

function solution(s: string): any {
  var map: any = {};
  for (var i = 0; i < s.length; i++) {
    var ch = s.charAt(i);
    map[ch] = (map[ch] || 0) + 1;
  }
  return map;
}

Best Answers

typescript - Approach 1
function solution(s: string): any {
  var map: any = {};
  for (var i = 0; i < s.length; i++) {
    var ch = s.charAt(i);
    map[ch] = (map[ch] || 0) + 1;
  }
  return map;
}