DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 383. Ransom Note

šŸš€ JavaScript Map (HashMap) Basics

  • Definition: A Map stores key-value pairs and maintains insertion order.
  • Key Types: Any (string, number, object, etc.).

āœ… Common Methods

const map = new Map();

// Add/Update
map.set('a', 1);

// Get
map.get('a'); // 1

// Check existence
map.has('a'); // true

// Delete
map.delete('a');

// Size
map.size; // 0

// Clear all
map.clear();
Enter fullscreen mode Exit fullscreen mode

šŸ”„ Iterating

for (const [key, value] of map) console.log(key, value);
map.forEach((value, key) => console.log(key, value));
Enter fullscreen mode Exit fullscreen mode

šŸ†š Map vs Object

Feature Map Object
Key Types Any String/Symbol
Order Maintains Unordered
Iteration Easy Complex
Performance Better for frequent updates Slower

āœ… Use Map when:

  • Keys are not just strings.
  • Frequent add/remove operations.
  • Need to maintain insertion order.

Javascript Code

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function (ransomNote, magazine) {
    let myMap = new Map();

    for (item of magazine) {
        myMap.set(item, (myMap.get(item) || 0) + 1);
    }
    for (item of ransomNote) {
        const count = myMap.get(item);
        if (!count) return false;
        myMap.set(item, count - 1);
    }

    return true
};
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More