Chapter[22]: Mastering Arrays: Solving 10 Problems from Basic to Advanced
Arrays are a fundamental part of programming. If you can solve array-based problems efficiently, you’re on your way to writing optimized and structured code. In this article, we’ll tackle 10 array problems, gradually increasing in difficulty.
In this article, we will solve 10 array problems step by step, categorized by type:
- Integer Arrays (Problems 1–3)
- String Arrays (Problems 4–6)
- Character Arrays (Problems 7–9)
- A Final Problem Combining All Three (Problem 10)
Let’s dive in!
Integer Array Problems
Find the Sum of All Elements (Basic)
Problem Statement
Given an integer array, find the sum of all its elements.
What Does the Problem Mean?
Imagine you have a list of numbers, and you need to find their total sum. For example, if the array is [2, 5, 7, 10]
, the output should be 24
.
Logical Solution
- Initialize a sum variable (
sum = 0
). - Loop through each element and add it to
sum
. - Print the final sum.
Textual Representation
Array: [2, 5, 7, 10]
Step 1: 2 + 5 = 7
Step 2: 7 + 7 = 14
Step 3: 14 + 10 = 24
Output: 24
Code Implementation
public class SumArray {
public static void main(String[] args) {
int[] numbers = {2, 5, 7, 10};
int sum = 0;
// Loop through the array and sum up elements
for (int num : numbers) {
sum += num;
}
System.out.println("Sum of array elements: " + sum);
}
}
Find the Second Largest Element (Medium)
Problem Statement
Given an integer array, find the second largest element.
What Does the Problem Mean?
If you have an array like [12, 34, 56, 78, 90]
, the largest element is 90
, and the second largest is 78
.
Logical Solution
- Initialize two variables:
largest
andsecondLargest
. - Iterate through the array:
- If a number is greater than
largest
, updatesecondLargest
first, thenlargest
. - Else if the number is greater than
secondLargest
, updatesecondLargest
.
Textual Representation
Array: [12, 34, 56, 78, 90]
Step 1: largest = 12, secondLargest = -∞ // Integer.MIN_VALUE
Step 2: largest = 34, secondLargest = 12
Step 3: largest = 56, secondLargest = 34
Step 4: largest = 78, secondLargest = 56
Step 5: largest = 90, secondLargest = 78
Output: 78
Code Implementation
public class SecondLargest {
public static void main(String[] args) {
int[] numbers = {12, 34, 56, 78, 90};
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : numbers) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest) {
secondLargest = num;
}
}
System.out.println("Second Largest Element: " + secondLargest);
}
}
Find Subarray with Maximum Sum (Advanced — Kadane’s Algorithm)
Problem Statement
Given an array, find the contiguous subarray with the maximum sum.
What Does the Problem Mean?
If you have an array like [-2, 3, 5, -1, 6, -3]
, the contiguous subarray [3, 5, -1, 6]
has the maximum sum, which is 13
. The goal is to find this efficiently.
Logical Solution (Kadane’s Algorithm)
Maintain two variables:
currentSum
→ Tracks the sum of the current subarray.maxSum
→ Stores the maximum sum encountered.
Traverse through the array:
- Add the current element to
currentSum
. - If
currentSum
is greater thanmaxSum
, updatemaxSum
. - If
currentSum
drops below zero, reset it to0
(because a negative sum won’t contribute to a larger sum).
Corrected Textual Representation
Array: [-2, 3, 5, -1, 6, -3]
Step 1: Start at -2 → currentSum = -2, maxSum = -2
Step 2: Add 3 → currentSum = 3 (reset since -2 was negative), maxSum = 3
Step 3: Add 5 → currentSum = 3 + 5 = 8, maxSum = 8
Step 4: Add -1 → currentSum = 8 - 1 = 7, maxSum remains 8
Step 5: Add 6 → currentSum = 7 + 6 = 13, maxSum = 13 (updated)
Step 6: Add -3 → currentSum = 13 - 3 = 10, maxSum remains 13
Final Output: 13
Code Implementation
public class MaxSubarraySum {
public static void main(String[] args) {
int[] numbers = {-2, 3, 5, -1, 6, -3};
int maxSum = Integer.MIN_VALUE, currentSum = 0;
for (int num : numbers) {
currentSum += num;
if (currentSum > maxSum) maxSum = currentSum;
if (currentSum < 0) currentSum = 0; // Reset if negative
}
System.out.println("Maximum Subarray Sum: " + maxSum);
}
}
This covers the integer array problems with increasing difficulty.
String Array Problems
4. Count the Number of Words in a Sentence (Basic)
Problem Statement
Given a sentence, count the number of words it contains.
What Does the Problem Mean?
For "Hello world! Java is fun."
, the word count is 4
.
Logical Solution
- Split the sentence using whitespace as a separator (
split(" ")
). - Count the resulting words.
Textual Representation
Sentence: "Hello world! Java is fun."
Split into: ["Hello", "world!", "Java", "is", "fun."]
Total Words: 4
Code Implementation
public class WordCount {
public static void main(String[] args) {
String sentence = "Hello world! Java is fun.";
String[] words = sentence.split(" ");
System.out.println("Word count: " + words.length);
}
}
5. Find the Longest Word in a Sentence (Medium)
Problem Statement
Find the longest word in a given sentence.
What Does the Problem Mean?
For "Automation makes life easier"
, the longest word is "Automation"
.
Logical Solution
- Split the sentence into words using
.split(" ")
. - Loop through and track the longest word.
Textual Representation
Sentence: "Automation makes life easier"
Words: ["Automation", "makes", "life", "easier"]
Longest word: "Automation"
Code Implementation
public class LongestWord {
public static void main(String[] args) {
String sentence = "Automation makes life easier";
String[] words = sentence.split(" ");
String longestWord = "";
for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
}
}
System.out.println("Longest word: " + longestWord);
}
}
6. Check If Two Strings Are Anagrams (Advanced)
Problem Statement
Check if two words are anagrams (contain the same letters in a different order).
What Does the Problem Mean?
"listen"
and "silent"
are anagrams, but "hello"
and "world"
are not.
Logical Solution
- Convert both words to lowercase.
- Sort the letters in both words.
- If they match, they are anagrams.
Textual Representation
Words: "listen" and "silent"
Sorted: "eilnst" and "eilnst" → Match
Output: They are anagrams.
Code Implementation
import java.util.Arrays;
public class AnagramCheck {
public static boolean areAnagrams(String str1, String str2) {
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
public static void main(String[] args) {
String word1 = "listen";
String word2 = "silent";
if (areAnagrams(word1, word2)) {
System.out.println(word1 + " and " + word2 + " are anagrams.");
} else {
System.out.println(word1 + " and " + word2 + " are not anagrams.");
}
}
}
Character Array Problems
7. Count Vowels and Consonants (Basic)
Problem Statement
Count the number of vowels and consonants in a character array.
What Does the Problem Mean?
For ['a', 'b', 'c', 'e', 'i']
, vowels = 3
, consonants = 2
.
Logical Solution
- Loop through characters.
- Check if each character is a vowel (
a, e, i, o, u
).
Textual Representation
Array: ['a', 'b', 'c', 'e', 'i']
Vowels: a, e, i → Count = 3
Consonants: b, c → Count = 2
Code Implementation
public class VowelConsonantCount {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'e', 'i'};
int vowels = 0, consonants = 0;
for (char ch : chars) {
if ("aeiou".indexOf(Character.toLowerCase(ch)) != -1) {
vowels++;
} else {
consonants++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
8. Reverse a Character Array (Medium)
Problem Statement
Reverse the elements in a character array.
What Does the Problem Mean?
For ['h', 'e', 'l', 'l', 'o']
, output should be ['o', 'l', 'l', 'e', 'h']
.
Logical Solution
- Use two pointers (one at start, one at end).
- Swap elements until pointers meet.
Textual Representation
Original: ['h', 'e', 'l', 'l', 'o']
Swap: h ↔ o → ['o', 'e', 'l', 'l', 'h']
Swap: e ↔ l → ['o', 'l', 'l', 'e', 'h']
Output: ['o', 'l', 'l', 'e', 'h']
Code Implementation
public class ReverseCharArray {
public static void main(String[] args) {
char[] arr = {'h', 'e', 'l', 'l', 'o'};
int left = 0, right = arr.length - 1;
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
System.out.println("Reversed array: " + Arrays.toString(arr));
}
}
9. Find the Most Frequent Character (Advanced)
1: Problem Statement
Find the most frequent character in a given string.
2: What Does the Problem Mean?
You are given a string, and you need to determine which character appears the most. Instead of using a HashMap
to store character counts, you must use an alternative method (like an array).
Example:
Input: "aabbbccddeee"
Output: 'b'
(since 'b' appears 3 times, which is the highest frequency)
3: Logical Solution
- Use an array of size 256 (since there are 256 ASCII characters). This will act as a frequency counter.
- Traverse the string and update the frequency array for each character.
- Find the character with the maximum frequency by scanning the array.
- Return the most frequent character encountered first if there is a tie.
4: Textual Representation
Consider the string "aabbbccddeee"
.
Step 1: Count Frequencies
'a' → ||
'a' → |||
'b' → ||
'b' → |||
'b' → ||||
'c' → ||
'c' → |||
'd' → ||
'd' → |||
'e' → ||
'e' → |||
'e' → ||||
Step 2: Find Maximum
'a' = 2
'b' = 3 ← (highest so far)
'c' = 2
'd' = 2
'e' = 3 ← (tie, but 'b' appeared first)
Step 3: Return 'b'
public class MostFrequentChar {
public static char findMostFrequentChar(String str) {
int[] freq = new int[256]; // Array to store frequency of each character
int maxFreq = 0;
char mostFrequent = '\0';
// Count frequency of each character
for (char ch : str.toCharArray()) {
freq[ch]++;
if (freq[ch] > maxFreq) { // Update max frequency and character
maxFreq = freq[ch];
mostFrequent = ch;
}
}
return mostFrequent;
}
public static void main(String[] args) {
String str = "aabbbccddeee";
System.out.println("Most Frequent Character: " + findMostFrequentChar(str));
}
}
Problem 10: Extract Integers, Characters, and Words from an Alphanumeric String
Problem Statement
You are given a mixed alphanumeric string containing numbers, words, and characters. Your task is to separate the elements into three different arrays:
- An integer array containing all the numbers.
- A character array containing all the individual characters (excluding spaces and numbers).
- A string array containing all the words (separated by spaces).
Explaining the Problem with an Example
Let’s say we have the following input string:
"I have 2 apples and 3 bananas."
We need to extract:
Numbers → [2, 3]
(Stored in an integer array)
Characters → ['I', 'h', 'a', 'v', 'e', 'a', 'p', 'p', 'l', 'e', 's', 'a', 'n', 'd', 'b', 'a', 'n', 'a', 'n', 'a', 's', '.']
Words → ["I", "have", "apples", "and", "bananas."]
Logical Solution (Step-by-Step Approach)
We will solve this problem in three steps:
Step 1: Extract Numbers and Store Them in an Integer Array
- Remove all non-numeric characters except spaces.
- Split the remaining string by spaces.
- Convert the string numbers into an integer array.
Step 2: Extract Characters and Store Them in a Character Array
- Remove all digits and spaces from the string.
- Convert the remaining characters into an array.
Step 3: Extract Words and Store Them in a String Array
- Remove all digits from the string.
- Split the cleaned-up string by spaces to get words.
Textual Representation
Input String: "I have 2 apples and 3 bananas."
Step 1: Extract Numbers
Original: "I have 2 apples and 3 bananas."
Keep Only Numbers: "2 3"
Convert to Integer Array: [2, 3]
Step 2: Extract Characters
Original: "I have 2 apples and 3 bananas."
Remove Numbers & Spaces: "Ihaveapplesandbananas."
Convert to Character Array: ['I', 'h', 'a', 'v', 'e', ..., 's', '.']
Step 3: Extract Words
Original: "I have 2 apples and 3 bananas."
Remove Numbers: "I have apples and bananas."
Convert to String Array: ["I", "have", "apples", "and", "bananas."]
Code Implementation
public class SeparateAlphanumeric {
public static void main(String[] args) {
String input = "I have 2 apples and 3 bananas."; // Input string
// Step 1: Extract numbers
String numStr = input.replaceAll("[^0-9]", " ").trim(); // Remove non-numeric characters
String[] numArray;
if (numStr.isEmpty()) {
numArray = new String[0]; // Empty array if string is empty
} else {
numArray = numStr.split("\\s+"); // Split based on spaces
}
int[] numbers = new int[numArray.length];
for (int i = 0; i < numArray.length; i++) {
numbers[i] = Integer.parseInt(numArray[i]); // Convert to integers
}
// Step 2: Extract characters (excluding spaces and numbers)
String charStr = input.replaceAll("[0-9 ]", ""); // Remove digits and spaces
char[] characters = charStr.toCharArray(); // Convert to char array
// Step 3: Extract words
String wordStr = input.replaceAll("[0-9]", "").trim(); // Remove numbers
String[] words = wordStr.split("\\s+"); // Split into words
// Print results
System.out.println("Numbers: " + java.util.Arrays.toString(numbers));
System.out.println("Characters: " + java.util.Arrays.toString(characters));
System.out.println("Words: " + java.util.Arrays.toString(words));
}
}
Code Breakdown (Explaining Every Line)
Step 1: Extracting Numbers
Sng numStr = input.replaceAll("[^0-9]", " ").trim();
[0-9]
→ Matches all numbers.[^0-9]
→ Matches everything except numbers and replaces them with spaces.trim()
→ Removes extra spaces from the beginning and end.
int[] numbers = new int[numArray.length];
for (int i = 0; i < numArray.length; i++) {
numbers[i] = Integer.parseInt(numArray[i]);
}
- Convert string numbers into an integer array using
Integer.parseInt()
.
Step 2: Extracting Characters
String charStr = input.replaceAll("[0-9 ]", ""); // Remove digits and spaces
char[] characters = charStr.toCharArray(); // Convert to char array
[0-9 ]
→ Matches numbers and spaces, replaces them with nothing (""
).toCharArray()
→ Converts the remaining letters into a character array.
Step 3: Extracting Words
String wordStr = input.replaceAll("[0-9]", "").trim(); // Remove numbers
String[] words = wordStr.split("\\s+"); // Split into words
[0-9]
→ Removes numbers but keeps spaces and letters.split("\\s+")
→ Splits the sentence into words.
Output Example
Numbers: [2, 3]
Characters: [I, h, a, v, e, a, p, p, l, e, s, a, n, d, b, a, n, a, n, a, s, .]
Words: [I, have, apples, and, bananas.]
This problem is a real-world use case that helps in data extraction from a messy input. You now have a clear understanding of how to separate numbers, characters, and words efficiently.
.
.
.
Happy Coding!