Day - 39 Sort Characters by Frequency The problem - Given a string s, sort it in decreasing order based on the frequency of characters. Return the sorted string. Example : s = "tree" → "eert" or "eetr" s = "cccaaa" → "aaaccc" or "cccaaa" Brute force - Count the frequencies of characters in both strings and then sort manually, but the time complexity will be O(n log n). Approach Used - •) Create HashMap to count character frequencies, iterate through the s.toCharArray() and use hm.put(char, hm.getOrDefault(char, 0) + 1). •) Create max heap PriorityQueue with custom comparator, PriorityQueue<Map.Entry<Character, Integer>> pq. •) And the comparator = (a, b) → b.getValue() - a.getValue(). •) Add all entries from HashMap - pq.addAll(hm.entrySet()). •) While pq is not empty. 1 - Poll entry from pq. 2 - Append character repeated by its frequency, String.valueOf(entry.getKey()).repeat(entry.getValue()). •) Return result.toString(). Complexity - Time - O(n + k log k), where n is string length, k is unique characters. Space - O(n), HashMap and result. Note - PriorityQueue with reverse comparator gives us characters in frequency order automatically. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
Sort Characters by Frequency in Java
More Relevant Posts
-
Day - 54 Copy List with Random Pointer The problem - A linked list has next and random pointers. Deep copy the list (create new nodes with same values and pointer relationships). Example : [[7,null],[13,0],[11,4],[10,2],[1,0]] → deep copied list Approach Used - •) Create HashMap<Node, Node> oldToNew. •) Traverse original list (curr = head) 1 - For each node, create new node with same value. 2 - Store mapping, oldToNew.put(curr, new Node(curr.val)). 3 - Move curr forward. •) Traverse original list again (curr = head) 1 - Set next, oldToNew.get(curr).next = oldToNew.get(curr.next). 2 - Set random, oldToNew.get(curr).random = oldToNew.get(curr.random). 3 - Move curr forward. •) Return oldToNew.get(head). Complexity - Time - O(n), two passes. Space - O(n), HashMap stores n mappings. Note - Use HashMap to store old→new node mapping. First pass creates nodes, second pass sets pointers #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day - 63 Combination Sum III The problem - Find all combinations of k numbers that sum to n, using only numbers 1-9, each number used at most once. Example : k = 3, n = 7 → [[1,2,4]] Brute Force - Generate all C(9, k) combinations, check each sum, still needs to enumerate all combinations. Approach Used - •) Initialize: Call findCombination(k, 1, n, new ArrayList<>(), ans) (start with number 1). •) findCombination(k, num, target, lst, ans), •) If (target == 0 && k == 0), found valid combination, add new ArrayList(lst) to ans and return. •) Recursive case, for num to 9, 1 - If i > target || k <= 0, break. 2 - Add i to lst. 3 - Recurse with k - 1 (need one less number), i + 1 (next number to try), target - i (remaining sum). 4 - Backtrack: remove i from lst. Complexity - Time - O(C(9, k) × k), C(9,k) combinations, k time to copy each. Space - O(k), recursion depth. Note - Loop from 1-9, add number, recurse with k-1 and target-num. Backtrack when target == 0 && k == 0! #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day - 65 Letter Combinations of Phone Number The problem - Given string of digits 2-9, return all possible letter combinations that the number could represent (like old phone keypads). Example : digits = "23" → ["ad","ae","af","bd","be","bf","cd","ce","cf"] Brute Force - Generate all combinations iteratively using nested loops - works but becomes unwieldy with variable input length. Approach Used - •)Create map, 2→"abc", 3→"def", 4→"ghi", 5→"jkl", 6→"mno", 7→"pqrs", 8→"tuv", 9→"wxyz" •) Handle edge case, if digits is null or empty, return empty list. •) Initialize, call backtrack(digits, 0, new StringBuilder(), res, map). •) Backtrack(digits, idx, comb, res, map), 1 - Base Condition, if idx == digits.length, add comb to res. 2 - Recursive case, get letters for current digit, String letters = map.get(digits.charAt(idx)). 3 - For each letter, append to comb, recurse with idx+1, backtrack(digits, idx + 1, comb, res, map). Remove last character, comb.deleteCharAt(comb.length() - 1). Complexity - Time - O(4^n × n), max 4 letters per digit, n to build each string. Space - O(n), recursion depth. Note - Use map for digit→letters. For each digit, try all its letters, recurse to next digit. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day - 60 Combination Sum II The problem - Given array (may contain duplicates) and target, return all unique combinations that sum to target. Each number can be used at most once. Example : candidates = [10,1,2,7,6,1,5], target = 8 → [[1,1,6],[1,2,5],[1,7],[2,6]] Brute Force - Generate all combinations and filter duplicates, exponential and inefficient. Approach Used - •) Sort the candidates array. •) Call findCombinations(ind, arr, target, ans, ds). •) Base case, if target == 0, found valid combination, add new ArrayList(ds) to ans and return. •) Recursive case, for loop from ind to arr.length 1 - If i > ind && arr[i] == arr[i-1], skip it as it is duplicate. 2 - If arr[i] > target, break 3 - Add arr[i] to ds, recurse with i+1, findCombinations(i + 1, arr, target - arr[i], ans, ds). 4 - Backtrack: remove arr[i] from ds. Complexity - Time - O(2^n), we skip duplicates and terminate early. Space - O(n), recursion depth. Note - Sort array, skip duplicates at same recursion level to avoid duplicate combinations. Sorting groups duplicates together, making it easy to detect and skip them with the condition arr[i] == arr[i-1]. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
📁 File Handling 🌊Character streams deal with Unicode characters 🌍 👉 They are meant for text, not raw binary data like byte stream.| ✔️ FileWriter → can create a file if it doesn’t exist ✨ ❌ FileReader → never creates a file 👉 If file doesn’t exist → FileNotFoundException 🚫 Reading rules 📖 ✔️ read() returns -1 at end of file 🛑 ✔️ Correct pattern: while ((ch = reader.read()) != -1) 🔁 File deletion 🗑️ ✔️ file.delete() ✔️ Returns boolean (true / false) ❓ Why no exception? 👉 Because streams are irrelevant for delete ❌ Character streams CANNOT update content in the middle of a file ✔️ Same rule as byte streams Why? 🤔 👉 Files are linear 📏 👉 There is no “insert here” operation 👉 You can only read forward or write forward What “update” actually means in Java 🧠 There is ONLY one way 👇 1️⃣ Read entire file (FileReader) 📖 2️⃣ Modify content in memory (String / StringBuilder) 🧩 3️⃣ Rewrite entire file (FileWriter) ✍️ ✅ This is the only real update mechanism Append ≠ Update ⚠️ 👉 Files store bytes; FileReader interprets bytes as characters, FileInputStream does not. GitHub Link: https://lnkd.in/g9843mcC 🔖Frontlines EduTech (FLM) #Java #JavaIO #FileHandling #ByteStream #CharacterStream #FileInputStream #FileReader #Unicode #JVM #JavaConcepts #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #BackendDevelopment #Programming #Java #FileHandling #CharacterStreams #Unicode #FileReader #FileWriter #BackendConcepts #LearningInPublic
To view or add a comment, sign in
-
-
Day 92/100 Problem Statement : Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal. Input: s1 = "sea", s2 = "eat" Output: 231 Solution : https://lnkd.in/gm8-CDmm public int minimumDeleteSum(String s1, String s2) { int m = s1.length(), n = s2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (s1.charAt(i) == s2.charAt(j)) { dp[i][j] = s1.charAt(i) + dp[i + 1][j + 1]; } else { dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]); } } } int total = 0; for (char c : s1.toCharArray()) total += c; for (char c : s2.toCharArray()) total += c; return total - 2 * dp[0][0]; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
Day - 61 Subsets II The problem - Given array that may contain duplicates, return all possible unique subsets. Example : candidates = [10,1,2,7,6,1,5], target = 8 → [[1,1,6],[1,2,5],[1,7],[2,6]] Brute Force - Generate all combinations iteratively, still exponential, but less elegant than recursion. Approach Used - •) Sort the nums array.nums.lengthcktrack(0, nums, subset, res). •) Base case, if i == nums.length, reached end, add new ArrayList(subset) to res and return. •) Recursive First case, include nums[i], add to subset, recurse with i+1, backtrack (remove). •) Recursive Second case, exclude nums[i], recurse with i+1 (don't add). Complexity - Time - O(2^n), each element include/exclude. Space - O(n), recursion depth. Note - Sort array. After excluding an element, skip all duplicates before next recursion to avoid duplicate subsets. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
📌 DSA Series — Day 3 | Arrays (Problem 1) Problem: Union of Two Arrays (with Duplicates) 🔹 Problem Understanding: Given two arrays, find the union of both arrays such that the result contains only unique elements, even if duplicates exist in the input arrays. 🔹 Approach (HashSet-based): Use a HashSet to automatically handle duplicates. Insert all elements from both arrays into the set. Convert the set to a list and sort it to return the union in ascending order. 🔹 Why this works: A Set guarantees uniqueness, which removes duplicates efficiently without manual checks. 🔹 Time Complexity: Insertion into HashSet: O(n + m) Sorting the result: O(k log k) (where k is the number of unique elements) 🔹 Space Complexity: O(n + m) 🔹 Java Implementation: class Solution { public static ArrayList<Integer> findUnion(int[] a, int[] b) { Set<Integer> lst = new HashSet<>(); for (Integer item : a) { lst.add(item); } for (Integer item : b) { lst.add(item); } ArrayList<Integer> response = new ArrayList<>(lst); Collections.sort(response); return response; } } 🔹 Key Insight: Using a HashSet simplifies the problem, but if both arrays are already sorted, a two-pointer approach can achieve the same result with O(1) extra space. 📈 Continuing my structured DSA problem-solving series. #DSA #Arrays #Java #HashSet #ProblemSolving #StriversA2Z #CodingJourney #GFG #LeetCode
To view or add a comment, sign in
-
-
🔥 Day 304 – Daily DSA Challenge! 🔥 Problem: 🎯 Combination Sum II Given an array of candidate numbers (with possible duplicates) and a target value, return all unique combinations where the chosen numbers sum to the target. 👉 Each number can be used at most once in a combination. 💡 Key Insights: 🔹 This is a classic backtracking + pruning problem. 🔹 Sorting the array is crucial to handle duplicates efficiently. 🔹 Skip repeated elements at the same recursion level to avoid duplicate combinations. 🔹 Once a number exceeds the remaining target, we can stop early (thanks to sorting). 🔹 Always move to i + 1 since each element can be used only once. ⚡ Optimized Plan: ✅ Sort the candidates array ✅ Use backtracking to explore all valid combinations ✅ Maintain a temporary list (cur) for the current path ✅ Add the path to result when target == 0 ✅ Skip duplicates using if (i > idx && a[i] == a[i - 1]) ✅ Backtrack after each recursive call ✅ Time Complexity: O(2ⁿ) in the worst case ✅ Space Complexity: O(n) (recursion stack + current combination) 💬 Challenge for you: 1️⃣ What happens if we remove sorting — how do duplicates affect the output? 2️⃣ How is this problem different from Combination Sum I? 3️⃣ Can you convert this recursive solution into an iterative one? #DSA #LeetCode #Backtracking #Recursion #ProblemSolving #Java #KeepCoding
To view or add a comment, sign in
-
-
𝗠𝗼𝘀𝘁 𝗗𝗦𝗔 𝗽𝗿𝗼𝗯𝗹𝗲𝗺𝘀 𝗱𝗼𝗻’𝘁 𝗻𝗲𝗲𝗱 𝘀𝗺𝗮𝗿𝘁𝗲𝗿 𝗰𝗼𝗱𝗲. 𝗧𝗵𝗲𝘆 𝗻𝗲𝗲𝗱 𝗹𝗲𝘀𝘀 𝗿𝗲𝗽𝗲𝗮𝘁𝗲𝗱 𝘄𝗼𝗿𝗸. 𝗗𝗮𝘆 𝟯/𝟯𝟬 – DSA Pattern: Prefix Sum 🧠 How to spot this pattern If the problem has: • Multiple range sum queries • Subarray sum questions • “Sum from index L to R” • Brute force recalculates sums again and again 👉 Think Prefix Sum 💡 Simple idea Instead of adding numbers every time: Precompute sums once Store sum till each index Reuse it whenever needed Do the work once, use it many times. ✏️ Pseudocode 𝙥𝙧𝙚𝙛𝙞𝙭[0] = 𝙖𝙧𝙧[0] 𝙛𝙤𝙧 𝙞 𝙛𝙧𝙤𝙢 1 𝙩𝙤 𝙣-1: 𝙥𝙧𝙚𝙛𝙞𝙭[𝙞] = 𝙥𝙧𝙚𝙛𝙞𝙭[𝙞-1] + 𝙖𝙧𝙧[𝙞] 𝙨𝙪𝙢(𝙡, 𝙧): 𝙞𝙛 𝙡 == 0: 𝙧𝙚𝙩𝙪𝙧𝙣 𝙥𝙧𝙚𝙛𝙞𝙭[𝙧] 𝙧𝙚𝙩𝙪𝙧𝙣 𝙥𝙧𝙚𝙛𝙞𝙭[𝙧] - 𝙥𝙧𝙚𝙛𝙞𝙭[𝙡-1] LeetCode example : https://lnkd.in/gwGqPN8W 🧩 Problems that use this • Range sum queries • Subarray sum equals K • Equilibrium index • Difference array problems 🔥 One rule to remember If you’re adding the same elements again and again, you’re missing Prefix Sum. Once you build the prefix array, 👉 each query becomes O(1). Tomorrow: Hashing / Frequency Map 👍 if this helped Comment “DSA” to follow the 30-day pattern series. #DSA #ProblemSolving #Java #CodingInterviews #LearningInPublic #30DaysOfDSA
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development