Counting Integer Frequencies with Negative Values in Java

Day 3 - Extending Frequency Logic to Handle Negative Integers Hello Connections, Continuing my DSA with Java journey, today I took yesterday’s concept of frequency mapping and applied it to a more flexible scenario - counting integer frequencies even when the numbers include negatives. Problem I Solved: Count the frequency of integers within a given range including negative values. Example: Range → max = 5, min = -5 Numbers → 1, -1, -3, -1, 4, 2 Output should show frequency for every number from -5 to +5 My Approach: Yesterday, I used ASCII values to map letters into array indexes. Today, I applied the exact same idea to integers. Step 1: Finding the Range: To store frequencies from min to max, I need an array that has enough slots for every integer in between. So the range is calculated using: range = max - min + 1; Step 2: Mapping Any Number to an Array Index: Since Java array indexes start from 0, we shift each number relative to min, index = number - min; This creates a direct-access table where every integer has its own slot. Understanding how to calculate the range and map numbers to indexes made this problem simple and elegant. It’s amazing how the same idea from Day 2 can scale to more complex scenarios and I think that’s the real beauty of DSA. Excited for day 4! #dsawithjava #dsa #java

  • text

To view or add a comment, sign in

Explore content categories