Counting Array Elements in Java

🧠 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

To view or add a comment, sign in

Explore content categories