This repository contains HashMap-based problems implemented in Java.
Each problem focuses on solving real-world challenges using hashing, frequency counting, and mapping.
- Problem: Read a string and count the frequency of each character.
- Approach:
- Use a HashMap<Character, Integer>.
- Traverse the string and update frequency.
- Example:
Input: "programming" Output: {p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}
- Problem: Given an array of strings, group all anagrams together.
- Approach:
- Sort each word’s characters → use sorted string as the key.
- Store original word in a list mapped to that key.
- Example:
Input: ["eat","tea","tan","ate","nat","bat"] Output: [["eat","tea","ate"], ["tan","nat"], ["bat"]]
- Problem: Find the first non-repeated character in a string.
- Approach:
- Use a LinkedHashMap to preserve insertion order.
- Count occurrences.
- Return first character with frequency = 1.
- Example:
Input: "swiss" Output: 'w'
- Problem: Sort a HashMap by its values.
- Approach:
- Convert
entrySet()into a list. - Sort using a custom comparator based on values.
- Insert back into
LinkedHashMapto maintain order. - Example:
Input: {a=5, b=2, c=8, d=3} Output: {b=2, d=3, a=5, c=8}
- Convert
- Problem: Find duplicate elements and their counts in an array.
- Approach:
- Use a HashMap<Integer, Integer> to store frequencies.
- Print numbers with count > 1.
- Example:
Input: [4, 5, 6, 4, 7, 5, 6, 6] Output: {4=2, 5=2, 6=3}