Arrays & Strings
šÆ Explain Like I'm 5...
Imagine you have a row of toy boxes lined up on a shelf! Each box has a number (like 0, 1, 2, 3...) and you can put one toy in each box.
š¦ Arrays - A Row of Boxes:
- ⢠Box 0: Put a red car š
- ⢠Box 1: Put a blue ball ā½
- ⢠Box 2: Put a yellow duck š¦
To get the ball, just say 'Give me what's in box 1!' Super fast! ā”
š¤ Strings - Letters in Boxes:
A string is just an array of letters! The word 'CAT' is like having 3 boxes:
- ⢠Box 0: 'C'
- ⢠Box 1: 'A'
- ⢠Box 2: 'T'
š Why Are They Useful?
- ⢠Arrays let you find things super fast if you know the box number!
- ⢠Strings let you work with words and sentences in your programs!
- ⢠Both are the building blocks for almost everything in programming!
š§ Basic Operations
Creating an Array
public class ArrayBasics { public static void main(String[] args) { // Creating an array - like setting up toy boxes! int[] numbers = new int[5]; // 5 empty boxes // Creating with values int[] myToys = {10, 20, 30, 40, 50}; // 5 boxes with toys! // String array String[] colors = {"red", "blue", "green"}; System.out.println("First number: " + myToys[0]); // Output: 10 System.out.println("First color: " + colors[0]); // Output: red }}Accessing Elements (Getting toys from boxes)
public class ArrayAccess { public static void main(String[] args) { int[] scores = {85, 90, 78, 92, 88}; // Access elements by index (box number) System.out.println("First score: " + scores[0]); // 85 System.out.println("Third score: " + scores[2]); // 78 System.out.println("Last score: " + scores[4]); // 88 // Loop through all elements System.out.println("All scores:"); for (int i = 0; i < scores.length; i++) { System.out.println("Score " + i + ": " + scores[i]); } // Enhanced for loop (easier way!) System.out.println("\nUsing enhanced for:"); for (int score : scores) { System.out.println(score); } }}Updating Elements (Putting new toys in boxes)
public class ArrayUpdate { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; System.out.println("Before: " + numbers[0]); // 1 // Update element (put new toy in box!) numbers[0] = 100; System.out.println("After: " + numbers[0]); // 100 // Update multiple elements for (int i = 0; i < numbers.length; i++) { numbers[i] = numbers[i] * 2; // Double each number! } System.out.println("Doubled array:"); for (int num : numbers) { System.out.print(num + " "); // 200 4 6 8 10 } }}š String Operations
String Basics
public class StringBasics { public static void main(String[] args) { // Creating strings String name = "Alice"; String greeting = "Hello"; // String length (how many letters?) System.out.println("Length: " + name.length()); // 5 // Access character at index System.out.println("First letter: " + name.charAt(0)); // A System.out.println("Last letter: " + name.charAt(4)); // e // Concatenation (joining strings) String message = greeting + " " + name + "!"; System.out.println(message); // Hello Alice! // String comparison String word1 = "cat"; String word2 = "cat"; String word3 = "dog"; System.out.println(word1.equals(word2)); // true System.out.println(word1.equals(word3)); // false }}String Manipulation
public class StringManipulation { public static void main(String[] args) { String text = "Hello World"; // Convert to uppercase/lowercase System.out.println(text.toUpperCase()); // HELLO WORLD System.out.println(text.toLowerCase()); // hello world // Substring (get part of string) System.out.println(text.substring(0, 5)); // Hello System.out.println(text.substring(6)); // World // Replace characters System.out.println(text.replace('o', '0')); // Hell0 W0rld // Check if string contains something System.out.println(text.contains("World")); // true System.out.println(text.contains("Java")); // false // Split string into array String sentence = "I love Java"; String[] words = sentence.split(" "); for (String word : words) { System.out.println(word); // I, love, Java } // StringBuilder for building strings efficiently StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(" "); sb.append("World"); System.out.println(sb.toString()); // Hello World }}š” Common Problems & Solutions
Problem 1: Reverse an Array
Flip the order of elements - like reading your toy boxes from right to left!
š” How it works:
Step 1: Use two pointers - one at start (left), one at end (right)
Step 2: Swap the elements at these positions
Step 3: Move left pointer right, right pointer left
Step 4: Repeat until pointers meet in middle
Example: [1, 2, 3, 4, 5] ā [5, 4, 3, 2, 1]
ā±ļø Time Complexity: O(n) - visit each element once
š¾ Space Complexity: O(1) - no extra space needed
public class ReverseArray { public static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; // Swap elements from both ends moving towards center while (left < right) { // Swap int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; System.out.print("Before: "); for (int num : numbers) { System.out.print(num + " "); } reverse(numbers); System.out.print("\nAfter: "); for (int num : numbers) { System.out.print(num + " "); // 5 4 3 2 1 } }}Problem 2: Check if String is Palindrome
A palindrome reads the same forwards and backwards, like 'racecar' or 'mom'!
š” How it works:
Step 1: Clean the string (lowercase, remove spaces)
Step 2: Use two pointers - one at start, one at end
Step 3: Compare characters at both positions
Step 4: If they don't match, it's NOT a palindrome
Step 5: Move pointers towards center and repeat
Examples:
ā "racecar" ā r-a-c-e-c-a-r (same forwards & backwards)
ā "mom" ā m-o-m (same both ways)
ā "hello" ā h-e-l-l-o vs o-l-l-e-h (different)
ā±ļø Time Complexity: O(n) - check each character
š¾ Space Complexity: O(1) - only use pointers
public class Palindrome { public static boolean isPalindrome(String str) { // Clean string: remove spaces and make lowercase str = str.toLowerCase().replaceAll(" ", ""); int left = 0; int right = str.length() - 1; while (left < right) { if (str.charAt(left) != str.charAt(right)) { return false; // Not matching! } left++; right--; } return true; // All characters matched! } public static void main(String[] args) { System.out.println(isPalindrome("racecar")); // true System.out.println(isPalindrome("hello")); // false System.out.println(isPalindrome("A man a plan a canal Panama")); // true System.out.println(isPalindrome("mom")); // true }}Problem 3: Find Maximum in Array
Find the biggest number in your array - like finding the tallest toy!
š” How it works:
Step 1: Start by assuming the first element is the maximum
Step 2: Look at each other element one by one
Step 3: If you find a bigger number, update the maximum
Step 4: After checking all elements, you have the maximum!
Visual Example:
Array: [3, 7, 2, 9, 1, 5]
⢠Start: max = 3
⢠Check 7: bigger! ā max = 7
⢠Check 2: smaller, skip
⢠Check 9: bigger! ā max = 9
⢠Check 1: smaller, skip
⢠Check 5: smaller, skip
ā Final answer: 9
ā±ļø Time Complexity: O(n) - check every element
š¾ Space Complexity: O(1) - only store one max value
public class FindMaximum { public static int findMax(int[] arr) { if (arr.length == 0) { throw new IllegalArgumentException("Array is empty!"); } int max = arr[0]; // Assume first is biggest // Check all others for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; // Found bigger one! } } return max; } public static void main(String[] args) { int[] numbers = {3, 7, 2, 9, 1, 5}; int maximum = findMax(numbers); System.out.println("Maximum: " + maximum); // 9 // Also find minimum int min = numbers[0]; for (int num : numbers) { if (num < min) { min = num; } } System.out.println("Minimum: " + min); // 1 }}Problem 4: Two Sum Problem
Find two numbers that add up to a target - a classic interview question!
š” How it works:
The Challenge: Find two numbers that add up to a target number
Smart Solution (Using HashMap):
Step 1: For each number, calculate what we NEED to make the target
(complement = target - current number)
Step 2: Check if we've seen that complement before (in HashMap)
Step 3: If yes, we found our pair! Return both indices
Step 4: If no, store current number in HashMap and continue
Visual Example:
Array: [2, 7, 11, 15], Target: 9
i=0: num=2, need 9-2=7, not in map yet ā store {2:0}
i=1: num=7, need 9-7=2, found in map! ā
Return [0, 1] ā numbers[0] + numbers[1] = 2 + 7 = 9
Why HashMap?
⢠Checking if number exists: O(1) super fast!
⢠Better than checking every pair: O(n²) slow
ā±ļø Time Complexity: O(n) - one pass through array
š¾ Space Complexity: O(n) - HashMap stores numbers
import java.util.HashMap;public class TwoSum { public static int[] twoSum(int[] nums, int target) { // HashMap to store number and its index HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; // Check if complement exists in map if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } // Store current number and index map.put(nums[i], i); } return new int[]{-1, -1}; // Not found } public static void main(String[] args) { int[] numbers = {2, 7, 11, 15}; int target = 9; int[] result = twoSum(numbers, target); if (result[0] != -1) { System.out.println("Indices: " + result[0] + ", " + result[1]); System.out.println("Numbers: " + numbers[result[0]] + " + " + numbers[result[1]] + " = " + target); // Output: 2 + 7 = 9 } }}š Key Points to Remember
- 1ļøā£Arrays have fixed size (can't easily add more boxes)
- 2ļøā£Accessing by index is O(1) - super fast!
- 3ļøā£Strings in Java are immutable (can't change, must create new ones)
- 4ļøā£Arrays are zero-indexed (first element is at index 0)
šŖ Practice Problems
- ⢠Remove duplicates from sorted array
- ⢠Rotate array by K positions
- ⢠Longest substring without repeating characters
- ⢠Valid anagram
- ⢠Merge two sorted arrays