Day 1 Basics of Java Arrays: Understand with Life Examples and Solve 15 LeetCode Challenges

Bikesh KumarBikesh Kumar
3 min read

β€œIt’s not about the destination, it’s about the clarity you gain with every step.”
β€” The Peaceful Coder


πŸ“… Day 1 β€” Topic: Arrays


🧠 Explanation

Imagine a row of empty tiffin boxes on your kitchen shelf.
Each box has a fixed position β€” Box 0, Box 1, Box 2...
You can fill them with anything: fruits, snacks, or even empty ones.
That, my friend, is an Array in programming.

Arrays are like those boxes β€” fixed-size containers storing similar items (numbers, strings, etc.), all lined up in order.


πŸ§ͺ Real-Life Example

Your shoe rack has 5 slots. You put 5 pairs of shoes in order.
Slot 0 β†’ Sandals, Slot 1 β†’ Sneakers...
You can directly go to Slot 3 and grab your formal shoes.

That's exactly how random access in arrays works:
You know the index, you get the value β€” instantly.


πŸ–ΌοΈ Image Reference

πŸ’» Java Syntax (with comments)

// Declare an array of size 5
int[] shoes = new int[5];

// Assign values
shoes[0] = 1;  // sandals
shoes[1] = 2;  // sneakers

// Access value at index 1
System.out.println(shoes[1]);  // Output: 2

πŸ“‹ Algorithm (How to Think About It)

  • 🟑 Step 1: Declare an array of fixed size

  • 🟒 Step 2: Use index (0-based) to insert values

  • πŸ”΅ Step 3: Access/update using the same index

  • βšͺ Step 4: Loop through for any operation

🎯 Key Points to Remember

  • Array size is fixed once declared.

  • Indexing starts from 0.

  • Can store only one data type.

  • You get O(1) access time.

  • Can't shrink/grow like magic β€” use ArrayList if needed.

πŸ“ 15 Beginner LeetCode Problems (Click to Practice)

Solution - Two Sum

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i=0;i<nums.length-1;i++)
        {
            for(int j=i+1;j<nums.length;j++)
            {
                if(nums[i]+nums[j]==target){
                     return new int[]{ i, j };
                }             
            }
        }
         return null;
    }   
}

Solution - Best Time to Buy and Sell Stock

class Solution {
    public int maxProfit(int[] prices) {
        int finalProfit=0;
        int minBuy=prices[0];
        for(int i=1;i<prices.length;i++){
            int profit=0;
            if(prices[i]-minBuy<0){
                minBuy=prices[i];
            }else{
                profit=prices[i]-minBuy;
                if(finalProfit<profit){
                    finalProfit=profit;
                }
            }
        }
        return finalProfit;
    }
}
0
Subscribe to my newsletter

Read articles from Bikesh Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bikesh Kumar
Bikesh Kumar

Engineer by profession, peaceful warrior by mindset. On a journey to master DSA & CP β€” one problem, one lesson, one day at a time.