Key-Value with Map<string, number>
Write a TypeScript function that takes a string and returns a Map
TypeScript's Map
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
Same char
Character frequencies
Empty string
Two a's
All unique
Algorithm Flow
Solution Approach
Use a Map with typed keys and values in TypeScript. The Map<K, V> generic type specifies the key and value types, ensuring type-safe get and set operations.
TypeScript infers Map types from constructor arguments. Map preserves insertion order and accepts any value type as keys, unlike plain objects which only accept strings and symbols.
Time O(1) per operation, Space O(n).
Best Answers
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;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
