This collection of 30 Java string exercises takes you from fundamental character-by-character manipulation to genuinely challenging, interview-style string problems.
Every exercise includes a Problem Statement, Purpose, Hint, and a Solution with Explanation, along with an alternative approach where a cleaner or more efficient option exists.
- Also, See: Java Exercises with over 20+ topic-wise sets and 575+ coding questions to practice.
- Practice questions using our Online Java Compiler
+ Table of Contents (30 Exercises)
Table of contents
- Exercise 1: Reverse a String
- Exercise 2: Palindrome Check
- Exercise 3: Vowel and Consonant Counter
- Exercise 4: Character Occurrence
- Exercise 5: Remove Whitespace
- Exercise 6: Digit-Only Check
- Exercise 7: Toggle Case
- Exercise 8: String Length Without .length()
- Exercise 9: Concatenation Alternative
- Exercise 10: Anagram Check
- Exercise 11: Reverse Words
- Exercise 12: First Non-Repeated Character
- Exercise 13: Count Words
- Exercise 14: Remove Duplicates
- Exercise 15: String Rotation
- Exercise 16: Capitalize Words
- Exercise 17: Highest Occurring Character
- Exercise 18: Custom parseInt
- Exercise 19: Substring Count
- Exercise 20: Split Without .split()
- Exercise 21: String Compression
- Exercise 22: Longest Substring Without Repeating Characters
- Exercise 23: All Permutations
- Exercise 24: Group Anagrams
- Exercise 25: Valid Parentheses
- Exercise 26: Roman to Integer
- Exercise 27: Longest Common Prefix
- Exercise 28: Custom indexOf
- Exercise 29: Word Break Problem
- Exercise 30: Longest Palindromic Substring
Exercise 1: Reverse a String
Problem Statement: Write a program to reverse a given string without using the built-in StringBuilder.reverse() method.
Purpose: This exercise helps you practice iterating over characters and building output manually, a core skill for understanding how string manipulation works under the hood.
Given Input: str = "hello"
Expected Output: Reversed String = olleh
▼ Hint
- Convert the string to a character array using
toCharArray(). - Loop through the array from the last index to the first.
- Append each character to a new string variable as you go.
- Print the final reversed string.
▼ Solution & Explanation
Explanation:
toCharArray(): Converts the string into a character array so each character can be accessed individually by index.for (int i = chars.length - 1; i >= 0; i--): Iterates through the array backward, starting from the last character.reversed += chars[i]: Appends each character to the result string, building it in reverse order.- Alternative: You could use
StringBuilder.reverse()for a one-liner, but the loop better illustrates how reversal works internally.
Exercise 2: Palindrome Check
Problem Statement: Create a method that checks if a given string reads the same backward as forward (e.g., “radar”, “madam”).
Purpose: This exercise helps you practice two-pointer comparison and boolean logic, a common pattern used in string validation problems.
Given Input: str = "madam"
Expected Output: Is Palindrome = true
▼ Hint
- Convert the string to lowercase to make the check case-insensitive.
- Use two pointers, one at the start and one at the end of the string.
- Compare characters at both pointers and move them toward the center.
- If all characters match, the string is a palindrome.
▼ Solution & Explanation
Explanation:
toLowerCase(): Normalizes the string so the comparison ignores letter case.leftandright: Two pointers that start at opposite ends of the string and move toward the middle.lower.charAt(left) != lower.charAt(right): Compares mirrored characters; a mismatch means the string is not a palindrome.- Alternative: You could reverse the string and compare it to the original, but the two-pointer approach avoids creating an extra string.
Exercise 3: Vowel and Consonant Counter
Problem Statement: Count the total number of vowels and consonants in a given string.
Purpose: This exercise helps you practice character classification and conditional counting, useful skills for text analysis tasks.
Given Input: str = "Hello World"
Expected Output:
Vowels = 3 Consonants = 7
▼ Hint
- Loop through each character of the string.
- Convert each character to lowercase for consistent comparison.
- Check if the character is one of
a, e, i, o, uto count vowels. - Count alphabetic characters that aren’t vowels as consonants, and skip spaces or punctuation.
▼ Solution & Explanation
Explanation:
str.toLowerCase().toCharArray(): Converts the string to lowercase and breaks it into individual characters for iteration.Character.isLetter(c): Ensures only alphabetic characters are counted, skipping spaces and punctuation.vowelChars.indexOf(c) != -1: Checks whether the character exists in the vowel set to classify it correctly.- Alternative: You could use a regular expression like
String.valueOf(c).matches("[aeiou]")instead ofindexOf(), though it adds overhead for single-character checks.
Exercise 4: Character Occurrence
Problem Statement: Find the number of times a specific character appears in a string.
Purpose: This exercise helps you practice simple counting logic, a foundational skill for frequency analysis and text processing.
Given Input: str = "programming", target = 'r'
Expected Output: Occurrences of 'r' = 2
▼ Hint
Loop through each character of the string and increment a counter whenever it matches the target character.
▼ Solution & Explanation
Explanation:
str.charAt(i): Retrieves the character at each index during iteration.str.charAt(i) == target: Compares the current character to the target character.count++: Increments the counter each time a match is found.- Alternative: You could use
str.chars().filter(ch -> ch == target).count()with Java streams for a more concise solution.
Exercise 5: Remove Whitespace
Problem Statement: Write a program to remove all spaces from a string, including both leading/trailing and internal spaces.
Purpose: This exercise helps you practice string filtering and reconstruction, a common technique in input sanitization and formatting tasks.
Given Input: str = " Hello World "
Expected Output: Result = "HelloWorld"
▼ Hint
- Loop through each character of the string.
- Skip the character if it is a space using a conditional check.
- Append all non-space characters to a new string.
- Print the resulting string, which will have no spaces at all.
▼ Solution & Explanation
Explanation:
str.charAt(i): Accesses each character in the string one at a time.c != ' ': Checks whether the current character is a space before deciding to keep it.result += c: Builds a new string containing only the non-space characters.- Alternative: You could use
str.replaceAll("\\s+", "")for a quicker built-in solution, but the loop shows how filtering works character by character.
Exercise 6: Digit-Only Check
Problem Statement: Verify if a string contains only numeric digits using regular expressions or character loops.
Purpose: This exercise helps you practice input validation, a key skill for form validation and data cleaning.
Given Input: str = "12345"
Expected Output: Is Digits Only = true
▼ Hint
- Check if the string is empty first, since an empty string shouldn’t count as digits only.
- Loop through each character and use
Character.isDigit()to verify it’s numeric. - If any character fails the check, the string is not digits only.
- Alternatively, use the regex pattern
"\\d+"withString.matches().
▼ Solution & Explanation
Explanation:
str.isEmpty(): Guards against treating an empty string as valid, since it contains no digits.Character.isDigit(c): Checks whether each character is a numeric digit.isDigitsOnly = false: Set as soon as a non-digit character is found, and the loop exits early.- Alternative: You could replace the loop with
str.matches("\\d+")for a one-line regex-based solution.
Exercise 7: Toggle Case
Problem Statement: Convert all lowercase characters to uppercase and vice versa in a given string.
Purpose: This exercise helps you practice character-level case manipulation, useful for building text formatting utilities.
Given Input: str = "Hello World"
Expected Output: Result = hELLO wORLD
▼ Hint
- Loop through each character of the string.
- Check if the character is uppercase using
Character.isUpperCase(). - Convert uppercase characters to lowercase and lowercase characters to uppercase.
- Append each converted character to build the final result.
▼ Solution & Explanation
Explanation:
Character.isUpperCase(c): Determines whether the current character is uppercase before converting it.Character.toLowerCase(c)/Character.toUpperCase(c): Flips the case of each letter accordingly.result.append(c): Keeps non-alphabetic characters, such as spaces, unchanged in the output.- Alternative: You could build a char array and modify it in place instead of using
StringBuilder, thoughStringBuilderis more efficient for repeated appends.
Exercise 8: String Length Without .length()
Problem Statement: Find the length of a string without using the standard .length() method.
Purpose: This exercise helps you practice manual iteration and exception handling, and builds intuition for how built-in methods work internally.
Given Input: str = "OpenAI"
Expected Output: Length = 6
▼ Hint
- Use a
try-catchblock withcharAt()and increment a counter until an exception is thrown. - The exception signals that you’ve gone past the last valid index of the string.
- Avoid calling
.length()directly on the String object anywhere in your logic. - Print the final counted length.
▼ Solution & Explanation
Explanation:
str.charAt(length): Attempts to access each character one index at a time, starting from zero.length++: Increments the counter after each successful access.StringIndexOutOfBoundsException: Signals that the index has gone past the end of the string, which stops the loop.- Alternative: You could use
str.toCharArray().length, which relies on the array’s length field rather than the String class’s own method.
Exercise 9: Concatenation Alternative
Problem Statement: Concatenate two strings without using the + operator or the .concat() method.
Purpose: This exercise helps you practice working with StringBuilder internals, useful for understanding string immutability in Java.
Given Input: str1 = "Hello", str2 = "World"
Expected Output: Result = HelloWorld
▼ Hint
- Create a
StringBuilderobject to hold the combined characters. - Use the
append()method to add characters without relying on+orconcat(). - Loop through each string’s characters individually if you want to avoid
append(String)too. - Convert the final
StringBuilderback to a String usingtoString().
▼ Solution & Explanation
Explanation:
StringBuilder builder: Provides a mutable buffer for combining characters without creating new String objects at each step.builder.append(c): Adds each character one at a time from both strings.builder.toString(): Converts the accumulated characters back into a single String.- Alternative: You could use
String.join("", str1, str2), which avoids+andconcat()while still being a built-in approach.
Exercise 10: Anagram Check
Problem Statement: Determine if two strings are anagrams of each other (e.g., “listen” and “silent”).
Purpose: This exercise helps you practice sorting and array comparison, a common technique in interview-style string problems.
Given Input: str1 = "listen", str2 = "silent"
Expected Output: Is Anagram = true
▼ Hint
- Remove any spaces and convert both strings to lowercase for a fair comparison.
- Convert each string to a character array using
toCharArray(). - Sort both character arrays using
Arrays.sort(). - Compare the sorted arrays using
Arrays.equals(); if they match, the strings are anagrams.
▼ Solution & Explanation
Explanation:
toLowerCase().replace(" ", ""): Normalizes both strings so case and spacing don’t affect the comparison.Arrays.sort(arr1): Sorts the character array so identical letters line up regardless of their original order.Arrays.equals(arr1, arr2): Compares the two sorted arrays element by element to check for an exact match.- Alternative: You could use a frequency count with a
HashMapfor each character instead of sorting, which avoids the sorting cost for large strings.
Exercise 11: Reverse Words
Problem Statement: Reverse the words in a given sentence while keeping the words themselves intact (e.g., “Java is fun” becomes “fun is Java”).
Purpose: This exercise helps you practice splitting text into tokens and reassembling them in a different order, a common technique in text processing.
Given Input: str = "Java is fun"
Expected Output: Result = fun is Java
▼ Hint
- Split the sentence into words using
split("\\s+"). - Loop through the resulting array from the last word to the first.
- Append each word to a result string, separated by spaces.
- Avoid adding a trailing space after the very last word.
▼ Solution & Explanation
Explanation:
str.split("\\s+"): Breaks the sentence into an array of words, handling multiple spaces between them.for (int i = words.length - 1; i >= 0; i--): Iterates through the word array backward.result.append(words[i]): Adds each word to the result in reverse order.- Alternative: You could convert the array to a
ListwithArrays.asList()and callCollections.reverse(), though it requires extra conversion steps.
Exercise 12: First Non-Repeated Character
Problem Statement: Find the first character in a string that does not repeat anywhere else.
Purpose: This exercise helps you practice frequency counting with a LinkedHashMap, useful for tracking counts while preserving insertion order.
Given Input: str = "swiss"
Expected Output: First Non-Repeated Character = w
▼ Hint
- Use a
LinkedHashMap<Character, Integer>to count occurrences while preserving character order. - Loop through the string once to populate the count map.
- Loop through the string again and return the first character with a count of 1.
- Handle the case where no unique character exists.
▼ Solution & Explanation
Explanation:
LinkedHashMap<Character, Integer>: Stores each character’s frequency while preserving the order characters were first seen.counts.getOrDefault(c, 0) + 1: Increments the count for each character, defaulting to zero if it hasn’t been seen yet.counts.get(c) == 1: Identifies the first character in the original string whose total count is exactly one.- Alternative: You could use a plain
int[26]array for lowercase letters instead of a map, which is faster but less flexible for non-alphabetic input.
Exercise 13: Count Words
Problem Statement: Count the total number of words in a sentence, accounting for multiple consecutive spaces.
Purpose: This exercise helps you practice text tokenization and whitespace handling, useful for parsing raw user input.
Given Input: str = " Java is fun "
Expected Output: Word Count = 3
▼ Hint
- Trim the string first to remove leading and trailing spaces.
- Split the trimmed string using a regex that matches one or more spaces, such as
"\\s+". - Count the number of elements in the resulting array.
- Handle the edge case where the trimmed string is empty, which should result in zero words.
▼ Solution & Explanation
Explanation:
str.trim(): Removes leading and trailing whitespace so it doesn’t create empty entries when splitting.trimmed.split("\\s+"): Splits the string on one or more consecutive spaces, treating them as a single delimiter.words.length: Gives the total number of words found after the split.- Alternative: You could loop character by character and count transitions from space to non-space, which avoids regex but takes more code.
Exercise 14: Remove Duplicates
Problem Statement: Remove all duplicate characters from a string so that every character appears only once.
Purpose: This exercise helps you practice tracking seen characters with a Set, a useful technique for deduplication tasks.
Given Input: str = "programming"
Expected Output: Result = progamin
▼ Hint
- Create a
LinkedHashSet<Character>to track characters that have already been seen while preserving order. - Loop through the string and add each character to the set.
- Since a
Setautomatically ignores duplicates, only unique characters remain. - Join the characters back into a single string for the final result.
▼ Solution & Explanation
Explanation:
LinkedHashSet<Character>: Stores each unique character while preserving the order in which they first appeared.seen.add(c): Adds each character; duplicates are automatically ignored by the Set.StringBuilder result: Rebuilds a string from the unique characters stored in the set.- Alternative: You could use a
boolean[]array indexed by character code to track seen characters, which is faster but limited to a known character range.
Exercise 15: String Rotation
Problem Statement: Check if one string is a rotation of another (e.g., “waterbottle” is a rotation of “erbottlewat”).
Purpose: This exercise helps you practice a clever concatenation trick for substring checks, a common interview technique.
Given Input: str1 = "waterbottle", str2 = "erbottlewat"
Expected Output: Is Rotation = true
▼ Hint
- First check that both strings have the same length; if not, one cannot be a rotation of the other.
- Concatenate the first string with itself to form a doubled string.
- Check if the second string appears anywhere within this doubled string using
contains(). - If it does, the second string is a rotation of the first.
▼ Solution & Explanation
Explanation:
str1.length() == str2.length(): Ensures both strings are comparable in length before checking rotation.str1 + str1: Creates a doubled string that contains every possible rotation of the original as a substring.doubled.contains(str2): Confirms whether the second string exists within the doubled version of the first.- Alternative: You could manually check each rotation with a loop and substring slicing, but the concatenation trick is far more efficient.
Exercise 16: Capitalize Words
Problem Statement: Capitalize the first letter of every word in a given sentence.
Purpose: This exercise helps you practice word-by-word transformation, useful for formatting titles or names.
Given Input: str = "hello java world"
Expected Output: Result = Hello Java World
▼ Hint
- Split the sentence into individual words using
split(" "). - For each word, capitalize the first character and keep the rest unchanged.
- Join the capitalized words back together with a single space between them.
- Handle empty strings carefully to avoid errors when accessing the first character.
▼ Solution & Explanation
Explanation:
str.split(" "): Breaks the sentence into an array of individual words.Character.toUpperCase(word.charAt(0)): Capitalizes only the first character of each word.word.substring(1): Keeps the remaining characters of the word unchanged.- Alternative: You could write it more compactly as
word.substring(0, 1).toUpperCase() + word.substring(1).
Exercise 17: Highest Occurring Character
Problem Statement: Find the character that appears the maximum number of times in a string.
Purpose: This exercise helps you practice frequency mapping and finding a maximum value, a pattern used across many counting problems.
Given Input: str = "programming"
Expected Output: Highest Occurring Character = r
▼ Hint
- Use a
LinkedHashMap<Character, Integer>to count how many times each character appears. - Loop through the string once to populate the frequency map.
- Loop through the map entries to find the character with the highest count.
- If there’s a tie, keep the character that was found first.
▼ Solution & Explanation
Explanation:
LinkedHashMap<Character, Integer>: Tracks how many times each character appears while preserving the order they were first seen.counts.getOrDefault(c, 0) + 1: Builds up the frequency count for each character across the string.entry.getValue() > maxCount: Uses a strict greater-than check so the first character to reach the highest count wins any tie.- Alternative: You could sort the entry set by value in descending order and take the first result, though a single pass is more efficient.
Exercise 18: Custom parseInt
Problem Statement: Convert a string representation of a number (like "1234") into an actual integer without using Integer.parseInt().
Purpose: This exercise helps you practice manual numeric parsing and digit arithmetic, and builds intuition for how numbers are represented internally.
Given Input: str = "1234"
Expected Output: Parsed Integer = 1234
▼ Hint
- Loop through each character of the string.
- Convert each character to its numeric value by subtracting the character code for
'0'. - Multiply the running result by 10 and add the new digit at each step.
- Handle a possible leading minus sign if you want to support negative numbers.
▼ Solution & Explanation
Explanation:
str.charAt(i) - '0': Converts a numeric character to its actual digit value using character code arithmetic.result * 10 + digit: Shifts the existing digits left by one place and adds the new digit, building the number left to right.isNegative: Tracks whether a leading minus sign was present so the final result can be negated if needed.- Alternative: You could process the string from right to left and multiply each digit by a power of ten, though the running total approach needs fewer variables.
Exercise 19: Substring Count
Problem Statement: Count how many times a specific substring appears inside a larger string.
Purpose: This exercise helps you practice sliding window substring search, a technique used in text search and pattern matching.
Given Input: str = "abababab", sub = "ab"
Expected Output: Occurrences of "ab" = 4
▼ Hint
- Use a loop with
indexOf()to repeatedly locate the substring, starting the search after each match. - Keep track of the current search position and update it after every successful find.
- Increment a counter each time the substring is located.
- Stop the loop when
indexOf()returns -1, meaning no more matches exist.
▼ Solution & Explanation
Explanation:
str.indexOf(sub, index): Searches for the substring starting from the given position and returns its index or -1 if not found.index += sub.length(): Moves the search position past the current match to find non-overlapping occurrences.count++: Increments the counter every time a match is found.- Alternative: You could use regex with
Matcher.find()in a loop, thoughindexOf()is simpler for a fixed, non-pattern substring.
Exercise 20: Split Without .split()
Problem Statement: Write a custom method to split a string into an array of substrings based on a delimiter character.
Purpose: This exercise helps you practice manual tokenization using an ArrayList and substring extraction, and builds intuition for how split() works internally.
Given Input: str = "apple,banana,cherry", delimiter = ','
Expected Output:
apple banana cherry
▼ Hint
- Create a
List<String>to hold the resulting substrings. - Loop through the string, tracking the start of the current segment.
- Whenever the delimiter character is found, extract the substring from the start position to that point and add it to the list.
- After the loop ends, add the final remaining segment to the list.
▼ Solution & Explanation
Explanation:
List<String> parts: Collects each extracted substring as the string is scanned.str.substring(start, i): Extracts the segment between the last delimiter and the current one.start = i + 1: Moves the start position past the delimiter to begin the next segment.- Alternative: You could convert the string to a char array and build segments manually with
StringBuilder, though tracking substring indices is simpler here.
Exercise 21: String Compression
Problem Statement: Implement a method to perform basic string compression using the counts of repeated characters (e.g., "aabcccccaaa" becomes "a2b1c5a3").
Purpose: This exercise helps you practice grouping consecutive characters and building output with counts, a basic form of data compression.
Given Input: str = "aabcccccaaa"
Expected Output: Result = a2b1c5a3
▼ Hint
- Loop through the string while keeping track of the current character and a running count.
- When the next character differs from the current one, append the character and its count to the result.
- Reset the count to 1 whenever a new character starts.
- After the loop ends, append the final character and its count.
▼ Solution & Explanation
Explanation:
str.charAt(i) == str.charAt(i - 1): Compares the current character to the previous one to detect a run of repeats.count++: Increases the running count while consecutive characters match.result.append(str.charAt(i - 1)); result.append(count): Writes out the completed character group once a different character is found.- Alternative: You could use a
HashMapto count all character frequencies, but that would lose the original ordering that compression relies on.
Exercise 22: Longest Substring Without Repeating Characters
Problem Statement: Find the length of the longest substring in a given string that contains no duplicate characters.
Purpose: This exercise helps you practice the sliding window technique with a HashSet, a widely used pattern for substring problems.
Given Input: str = "abcabcbb"
Expected Output: Longest Substring Length = 3
▼ Hint
- Use two pointers to represent a sliding window over the string.
- Use a
HashSetto track characters currently inside the window. - Expand the window by moving the right pointer, and shrink it by moving the left pointer whenever a duplicate is found.
- Track the maximum window size seen during the process.
▼ Solution & Explanation
Explanation:
Set<Character> window: Tracks which characters currently exist within the sliding window.while (window.contains(c)): Shrinks the window from the left until the duplicate character is removed.maxLength = Math.max(maxLength, right - left + 1): Updates the largest window size found so far after each expansion.- Alternative: You could use a
HashMap<Character, Integer>to store the last seen index of each character, letting you jump the left pointer directly instead of shrinking one step at a time.
Exercise 23: All Permutations
Problem Statement: Find and print all possible permutations of a given string.
Purpose: This exercise helps you practice recursive backtracking, a foundational technique for generating combinatorial results.
Given Input: str = "abc"
Expected Output:
abc acb bac bca cab cba
▼ Hint
- Use a recursive helper method that builds up a partial permutation as it goes.
- At each recursive step, try adding each remaining unused character to the current partial string.
- When the partial string reaches the full length of the input, print it as a completed permutation.
- Use backtracking so a character removed from the current path can be reused in a different position.
▼ Solution & Explanation
Explanation:
current.length() == str.length(): Detects when a full permutation has been built and prints it.current.indexOf(str.charAt(i)) != -1: Skips characters that are already used in the current partial permutation.permute(str, current + str.charAt(i)): Recurses with the chosen character appended, exploring one branch of the decision tree.- Alternative: You could swap characters in place and recurse over index ranges instead of building new strings each time, avoiding repeated
indexOf()lookups.
Exercise 24: Group Anagrams
Problem Statement: Given an array of strings, group the anagrams together into separate lists.
Purpose: This exercise helps you practice using a sorted string as a map key to group related items, a common technique for classification problems.
Given Input: words = {"eat", "tea", "tan", "ate", "nat", "bat"}
Expected Output:
[eat, tea, ate] [tan, nat] [bat]
▼ Hint
- Create a
Map<String, List<String>>to group words by a common key. - For each word, sort its characters to produce a canonical key, since anagrams always produce the same sorted key.
- Add the word to the list associated with that key, creating the list first if it doesn’t exist yet.
- After processing all words, print each list of grouped anagrams.
▼ Solution & Explanation
Explanation:
Arrays.sort(chars): Produces a canonical, sorted version of each word so anagrams end up with an identical key.new String(chars): Converts the sorted character array back into a string usable as a map key.groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word): Creates a new list for a key if needed, then adds the current word to it.- Alternative: You could use a character frequency count as the key instead of sorting, which avoids the sort cost but requires building a custom key string.
Exercise 25: Valid Parentheses
Problem Statement: Given a string containing just the characters (, ), {, }, [ and ], determine if the input string is valid.
Purpose: This exercise helps you practice using a Stack for matching bracket pairs, a classic pattern for parsing balanced expressions.
Given Input: str = "{[()]}"
Expected Output: Is Valid = true
▼ Hint
- Use a
Deque<Character>as a stack to keep track of opening brackets as you encounter them. - When you see a closing bracket, check if it matches the type of bracket on top of the stack.
- If it matches, pop the stack; if it doesn’t match or the stack is empty, the string is invalid.
- After processing the entire string, it is valid only if the stack is empty.
▼ Solution & Explanation
Explanation:
Deque<Character> stack: Acts as a stack to track opening brackets in the order they appear.stack.push(c): Pushes an opening bracket onto the stack whenever one is encountered.stack.pop()and the matching checks: Ensures each closing bracket corresponds to the most recently opened bracket of the same type.- Alternative: You could use a
Map<Character, Character>to pair closing brackets with their opening counterparts, simplifying the matching condition into a single lookup.
Exercise 26: Roman to Integer
Problem Statement: Convert a given Roman numeral string (e.g., "XIV") into its corresponding integer value.
Purpose: This exercise helps you practice handling special-case subtraction rules with a lookup map, useful for parsing structured notations.
Given Input: str = "XIV"
Expected Output: Integer Value = 14
▼ Hint
- Create a
Map<Character, Integer>that assigns a numeric value to each Roman numeral symbol. - Loop through the string, comparing each symbol’s value to the value of the symbol that follows it.
- If a symbol’s value is less than the next symbol’s value, subtract it from the total instead of adding it.
- Otherwise, add the symbol’s value to the running total as normal.
▼ Solution & Explanation
Explanation:
Map<Character, Integer> values: Provides a quick lookup for the numeric value of each Roman numeral symbol.current < values.get(str.charAt(i + 1)): Detects subtractive notation, such as "IV", where a smaller value precedes a larger one.total -= current/total += current: Adjusts the running total based on whether the current symbol should be subtracted or added.- Alternative: You could process the string from right to left, comparing each symbol only to the previous maximum seen so far, which avoids look-ahead indexing.
Exercise 27: Longest Common Prefix
Problem Statement: Find the longest common prefix string amongst an array of strings.
Purpose: This exercise helps you practice character-by-character comparison across multiple strings, useful for autocomplete and search features.
Given Input: words = {"flower", "flow", "flight"}
Expected Output: Longest Common Prefix = fl
▼ Hint
- Start by assuming the first string in the array is the common prefix.
- Compare this prefix against each subsequent string, shortening it whenever it doesn't match.
- Use
startsWith()to check if a string begins with the current prefix candidate. - Stop early if the prefix becomes empty, since no common prefix can exist at that point.
▼ Solution & Explanation
Explanation:
String prefix = words[0]: Initializes the prefix candidate as the entire first word.words[i].startsWith(prefix): Checks whether the current word begins with the prefix candidate.prefix.substring(0, prefix.length() - 1): Trims one character off the end of the prefix whenever a mismatch is found.- Alternative: You could compare characters at each index position across all words simultaneously, stopping at the first index where they diverge.
Exercise 28: Custom indexOf
Problem Statement: Implement Java's String.indexOf() functionality manually to find the starting index of a substring inside a main string.
Purpose: This exercise helps you practice manual substring matching, and builds intuition for how pattern search works without relying on built-in methods.
Given Input: str = "hello world", sub = "world"
Expected Output: Index = 6
▼ Hint
- Loop through the main string, treating each position as a possible starting point for a match.
- At each position, check if the substring matches the characters starting there by comparing character by character.
- If all characters match, return the current starting index immediately.
- If no match is found after checking every position, return -1.
▼ Solution & Explanation
Explanation:
for (int i = 0; i <= str.length() - sub.length(); i++): Limits the starting positions checked so the substring never runs past the end of the main string.str.charAt(i + j) != sub.charAt(j): Compares each character of the substring against the corresponding character in the main string.result = i: Records the starting index as soon as a full match is confirmed.- Alternative: You could use more advanced algorithms like KMP for better performance on large inputs, though the brute-force approach is easier to follow for smaller strings.
Exercise 29: Word Break Problem
Problem Statement: Given a string and a dictionary of words, determine if the string can be segmented into a space-separated sequence of one or more dictionary words.
Purpose: This exercise helps you practice dynamic programming with a boolean array, a foundational technique for problems involving optimal substructure.
Given Input: str = "leetcode", dictionary = {"leet", "code"}
Expected Output: Can Be Segmented = true
▼ Hint
- Create a boolean array where each index represents whether the substring up to that point can be segmented.
- Mark the first position as true, since an empty prefix is trivially valid.
- For each position, check all earlier positions to see if the substring between them is a dictionary word and the earlier position is already valid.
- The final answer is whether the last position in the array is marked true.
▼ Solution & Explanation
Explanation:
boolean[] dp: Tracks whether the substring from the start up to each index can be fully segmented into dictionary words.dp[0] = true: Represents the base case of an empty string, which requires no words to segment.dp[j] && dictionary.contains(str.substring(j, i)): Checks if a valid split point exists where the earlier part is segmentable and the remaining part is a dictionary word.- Alternative: You could solve this recursively with memoization instead of a bottom-up array, though the iterative approach avoids the overhead of repeated function calls.
Exercise 30: Longest Palindromic Substring
Problem Statement: Find the longest substring within a given string that is a valid palindrome.
Purpose: This exercise helps you practice the expand-around-center technique, an efficient approach for palindrome-related problems.
Given Input: str = "babad"
Expected Output: Longest Palindromic Substring = bab
▼ Hint
- For each index in the string, treat it as the center of a potential palindrome and expand outward.
- Check both odd-length palindromes (single character center) and even-length palindromes (two character center).
- Expand outward from each center as long as the characters on both sides match.
- Keep track of the longest palindrome found across all centers.
▼ Solution & Explanation
Explanation:
expandAroundCenter(str, i, i): Checks for the longest odd-length palindrome centered at indexi.expandAroundCenter(str, i, i + 1): Checks for the longest even-length palindrome centered between indicesiandi + 1.start = i - (len - 1) / 2: Calculates the starting index of the longest palindrome found so far, based on its center and length.- Alternative: You could use dynamic programming with a 2D boolean table to track palindromic substrings, though the expand-around-center approach uses less memory.

Leave a Reply