🧠 Problem: Count Frequency of Each Number in an Array 📌 Given: An integer array: int[] arr = {12,54,8,7,12,32,12,54}; 📌 Task: Count how many times each number appears in the array. 📌 Expected Output: [12=3,54=2,8=1,7=1,32=1] NOTE : WITHOUT HASHMAP public class NumberCount2D { public static void main(String[] args) { int[] arr = {12,54,8,7,12,32,12,54}; // 2D array // Column 0 → number // Column 1 → count int[][] ansArr = new int[arr.length][2]; int size = 0; // tracks how many unique elements we stored // Traverse original array for (int num : arr) { boolean found = false; // Check if number already exists in ansArr for (int i = 0; i < size; i++) { // If number matches existing number if (ansArr[i][0] == num) { ansArr[i][1]++; // increase count found = true; break; // stop checking } } // If number not found, store it with count = 1 if (!found) { ansArr[size][0] = num; // store number ansArr[size][1] = 1; // first occurrence size++; // move to next row } } // Print result for (int i = 0; i < size; i++) { System.out.println(ansArr[i][0] + " = " + ansArr[i][1]); } } } #java #springboot #dsa #leetcode
Counting Array Elements in Java
More Relevant Posts
-
🚀 Day 18/100 – Find the Difference of Two Arrays. Today I solved the problem Find the Difference of Two Arrays. 🔹 Problem: Given two integer arrays nums1 and nums2, return a list of two lists: Elements present in nums1 but not in nums2 Elements present in nums2 but not in nums1 Example: Input: nums1 = [1,2,3] nums2 = [2,4,6] Output: [[1,3], [4,6]]. 🧠 Approach: 1️⃣ First convert both arrays into HashSet to remove duplicates and allow fast lookup. 2️⃣ Traverse set1 If an element is not present in set2, add it to result list a. 3️⃣ Traverse set2 If an element is not present in set1, add it to result list b. 4️⃣ Return both lists as result. HashSet helps because checking presence takes O(1) time. ⏱ Time Complexity Creating sets → O(n + m) Checking elements → O(n + m) ✅ Overall Time Complexity: O(n + m) ✅ Space Complexity: O(n + m). ✨ What I Learned: How to use HashSet to remove duplicate elements from arrays. How HashSet provides O(1) lookup time, making comparisons faster. How to find unique elements between two arrays efficiently. Improved understanding of Set operations and array traversal in Java. #Day18 #100DaysOfCode #LeetCode #Java #DSA #Consistency
To view or add a comment, sign in
-
-
☕ @SpringBootApplication — The Magic Annotation Unpacked One annotation to rule them all. But do you know what's actually inside it? @SpringBootApplication is a convenience annotation that combines three powerful ones: @SpringBootApplication // is equivalent to: @Configuration @EnableAutoConfiguration @ComponentScan public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } Here's what each does: • @Configuration — marks this class as a source of bean definitions (replaces XML config) • @ComponentScan — tells Spring to scan the current package and subpackages for @Component, @Service, @Repository, @Controller • @EnableAutoConfiguration — the real magic: Spring Boot reads your classpath and auto-configures beans (e.g., sees H2 → configures DataSource automatically) You can customize the scan: @SpringBootApplication(scanBasePackages = {"com.myapp.service", "com.myapp.api"}) Or exclude an auto-configuration you don't want: @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #SpringFramework
To view or add a comment, sign in
-
Day - 99 Insert into a Binary Search Tree The problem - Given the root node of a binary search tree (BST) and a value to insert into the tree, return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. Brute Force - Perform inorder traversal to collect all values, add the new value, sort the array, then rebuild the BST from the sorted array. This gives O(n log n) time complexity due to sorting and is unnecessarily complex since BST properties allow direct insertion. Approach Used - •) If root == null, return new TreeNode(val), found the insertion position. •) If root.val > val, value is smaller, insert in left subtree, root.left = insertIntoBST(root.left, val). •) Else (when root.val < val), value is larger, insert in right subtree, root.right = insertIntoBST(root.right, val). •) Return root. Complexity - Time - O(h), where h = height of tree. Space - O(h), recursion stack depth. Note - BST insertion leverages the binary search property: compare the value with current node, go left if smaller, right if larger. Recursively traverse until finding an empty position (null), then create and return the new node. The recursion naturally updates parent pointers as it backtracks, maintaining tree structure without explicit parent tracking. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🚀Day 98 of construct Binary search Tree from Preorder traversal. The Problem given an Array of Integers preorder, which represents the preorder traversal of BST (i.e., binary search Tree) construct the tree and return it's root guaranteed that there is always possible to find a binary tree with the given requirements for the given taste cases. Brute force - sort the preorder array to get inorder traversal, then use both preorder and inorder arrays to reconstruct the BST) ( like standard tree construction.) this gives O(n log n ) time due to sorting, which is inefficient when BST properties can guide direct construction. Approach used - •) if order. length ==0, return null ( empty tree). •) create root with first element, root = new tree node (Preorder [0]). •) return root. Helper function - insert Treenode root int val) •if val < root. val , insert in left subtree, - if root.left == null, create node , root left = new tree node( val). - Else recurse left , insert (root, left, val). •) Else ( when Val > root Val ), insert in right subtree, - if root. right == null, crate node , root right = new Tree node ( val ) - Else , recurse right , insert ( root. right, val ). complexity Time - O ( n × h ) , where h = height of tree is a number of nodes. Space - O( h), recursion stack depth. Note - preorder traversal's first element is always the root. By leveraging BST insertion rules . ( smaller values go left , larger go right ), we can sequentially insert each element from the preorder array. each insertion automatically finds the correct position building the BST without needing inorder traversal or sorting. #Java #LearnToCode #Problemsolving #DSA #coding
To view or add a comment, sign in
-
-
Day - 103 Construct Binary Search Tree from Preorder Traversal The problem - Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. Brute Force - Sort the preorder array to get inorder traversal, then use both preorder and inorder arrays to reconstruct the BST (like standard tree construction). This gives O(n log n) time due to sorting, which is inefficient when BST properties can guide direct construction. Approach Used - •) If preorder.length == 0, return null (empty tree). •) Create root with first element, root = new TreeNode(preorder[0]). •) For i = 1 to preorder.length - 1, insert each element, insert(root, preorder[i]). •) Return root. Helper Function - insert(TreeNode root, int val) •) If val < root.val, insert in left subtree, - If root.left == null, create node, root.left = new TreeNode(val). - Else, recurse left, insert(root.left, val). •) Else (when val > root.val), insert in right subtree, - If root.right == null, create node, root.right = new TreeNode(val) - Else, recurse right, insert(root.right, val). Complexity - Time - O(n x h), where h = height of tree, n is number of nodes. Space - O(h), recursion stack depth. Note - Preorder traversal's first element is always the root. By leveraging BST insertion rules (smaller values go left, larger go right), we can sequentially insert each element from the preorder array. Each insertion automatically finds the correct position, building the BST without needing inorder traversal or sorting. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Tried solving it with pure backtracking… but couldn’t optimize it efficiently without bitmasking. Here’s the approach that finally worked LeetCode 698 – Partition to K Equal Sum Subsets 🧠 Approach (Backtracking + Bitmasking + Memoization) We need to divide the array into k subsets such that each subset has equal sum. 🔹 Step 1: Feasibility Check Compute total sum If sum % k != 0 → return false 🔹 Step 2: Fix Target Each subset must have sum = target = sum / k 🔹 Step 3: Use Bitmask for State Represent picked elements using a bitmask mask helps track which elements are already used 🔹 Step 4: Build Subsets Recursively Keep adding unused elements to currSum If currSum == target → one subset is formed → Move to next subset (k - 1) and reset sum 🔹 Step 5: Memoization (Game Changer 🚀) Store results using mask If a configuration already failed → skip it ⚡ Key Insight Instead of managing k subsets explicitly: ->Focus on filling one subset at a time ->Reduce the problem (k) step by step ⏱️ Time Complexity O(N * 2^N) in worst case 2^N states from bitmask For each state, up to N choices ✔️ Memoization helps prune repeated states heavily 💬 Takeaway: Pure backtracking hits performance limits here — combining it with bitmasking + memoization is what makes it pass efficiently. #LeetCode #Backtracking #Bitmasking #Memoization #DSA #Java #CodingInterview
To view or add a comment, sign in
-
-
LeetCode 83 — Remove Duplicates from Sorted List This problem gives the head of a sorted linked list and asks to remove all duplicate values so that each element appears only once. Since the list is already sorted, duplicate values always appear next to each other. The task is simply to skip repeated nodes while keeping the original order of the list. Example : Input : 1 → 1 → 2 → 3 → 3 Output : 1 → 2 → 3 Approach used — Single Pass Pointer Traversal Because the list is sorted, the solution can be done in one traversal. Two pointers are used during traversal : - One pointer (a) keeps track of the last unique node. - Another pointer (b) scans the list forward. When both nodes have the same value, the duplicate node is skipped. When a new value appears, the unique node is connected to it. At the end, the last node’s next pointer is set to null to ensure the list ends correctly. This approach works in O(n) time and O(1) extra space. #leetcode #datastructures #linkedlist #java #problemSolving
To view or add a comment, sign in
-
-
Day - 87 Binary Tree Level Order Traversal The problem - Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level). Each level should be represented as a separate list. Brute Force - Use recursive DFS to traverse the tree while tracking depth. Store nodes at each depth level in separate lists. This gives O(n) time but requires complex depth tracking and is less intuitive than an iterative approach. Approach Used - •) Create res = new ArrayList<>(), queue = new ArrayDeque<>(). •) If root == null, return empty res. •) Add root to queue. •) While queue is not empty, 1 - Get current level size: size = queue.size(). 2 - Create list = new ArrayList<>(). 3 - While size > 0, - Poll node from queue, node = queue.poll(). - If node.left != null, add to queue: queue.add(node.left). - If node.right != null, add to queue: queue.add(node.right). - Add node value to current level: list.add(node.val). - Decrement size—. 4 - Add current level to result, res.add(list). •) Return res. Complexity - Time - O(n), where n = number of nodes. Space - O(w), where w = maximum width of tree. Note - Use BFS with a queue to traverse level by level. By capturing the queue size at the start of each iteration, we know exactly how many nodes belong to the current level. Process all nodes in that level, adding their children to the queue for the next level. This naturally groups nodes by level without needing depth tracking. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
LeetCode 1593 – Split a String Into the Max Number of Unique Substrings An ideal problem to understand Backtracking. The task is simple but tricky: Split a string into substrings such that all substrings are unique, and maximize the number of splits. 🚀 Approach (Backtracking) 1. Start from index i and try every possible substring s[i...j]. 2. If the substring is not already used (checked using a HashSet), we: add it to the set recursively explore the remaining string starting from j + 1 3. Each recursive call increases the current split count. 4. When we reach the end of the string (i >= length), we update the maximum number of unique splits. 5. After recursion, we remove the substring from the set (backtrack) so other possibilities can be explored. # Core Backtracking Pattern Choose → Explore → Undo Choose: Add substring to the set Explore: Recurse for the remaining string Undo: Remove substring to try other partitions Backtracking explores all possible partitions, but the HashSet ensures no substring repeats, giving the maximum valid split. Perfect example of how recursion + state tracking can systematically search the solution space. #LeetCode #Backtracking #Java #DSA #CodingInterview #Recursion
To view or add a comment, sign in
-
-
Day 11/30 – LeetCode streak Today’s problem: Sort Integers by The Number of 1 Bits You have to sort an array by popcount first (fewer 1s come earlier), and if two numbers have the same count, sort them by their actual value. Instead of using 'Arrays.sort' with a comparator, I tried writing the sort logic myself with insertion sort: - For each element, treat it as 'key' and move larger elements (based on custom “bit count, then value” order) one step to the right. - 'Swap(a, b)' returns true if 'a' should come after 'b' in the final order, using a manual 'countBits' function to compare the number of 1s. - If bit counts differ, the one with more 1s is considered “greater”; if they’re equal, compare the raw integers. Day 11 takeaway: This was a nice chance to practice writing a custom sort order from scratch—once the comparison rule is clear (“by 1-bits, then by value”), the rest is just plugging that into any sorting algorithm. #leetcode #dsa #java #bitmanipulation #sorting
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