PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Online Compilers▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Java Exercises » Java String Exercises: 30 Coding Problems with Solutions

Java String Exercises: 30 Coding Problems with Solutions

Updated on: July 6, 2026 | Leave a Comment

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
class ReverseString {
    public void reverse(String str) {
        char[] chars = str.toCharArray();
        String reversed = "";

        for (int i = chars.length - 1; i >= 0; i--) {
            reversed += chars[i];
        }

        System.out.println("Reversed String = " + reversed);
    }
}

public class Main {
    public static void main(String[] args) {
        ReverseString reverseString = new ReverseString();
        reverseString.reverse("hello");
    }
}Code language: Java (java)

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
class PalindromeChecker {
    public void checkPalindrome(String str) {
        String lower = str.toLowerCase();
        boolean isPalindrome = true;
        int left = 0;
        int right = lower.length() - 1;
        while (left < right) {
            if (lower.charAt(left) != lower.charAt(right)) {
                isPalindrome = false;
                break;
            }
            left++;
            right--;
        }
        System.out.println("Is Palindrome = " + isPalindrome);
    }
}

public class Main {
    public static void main(String[] args) {
        PalindromeChecker palindromeChecker = new PalindromeChecker();
        palindromeChecker.checkPalindrome("madam");
    }
}Code language: Java (java)

Explanation:

  • toLowerCase(): Normalizes the string so the comparison ignores letter case.
  • left and right: 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, u to count vowels.
  • Count alphabetic characters that aren’t vowels as consonants, and skip spaces or punctuation.
▼ Solution & Explanation
class VowelConsonantCounter {
    public void countVowelsAndConsonants(String str) {
        int vowels = 0;
        int consonants = 0;
        String vowelChars = "aeiou";

        for (char c : str.toLowerCase().toCharArray()) {
            if (Character.isLetter(c)) {
                if (vowelChars.indexOf(c) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }

        System.out.println("Vowels = " + vowels);
        System.out.println("Consonants = " + consonants);
    }
}

public class Main {
    public static void main(String[] args) {
        VowelConsonantCounter vowelConsonantCounter = new VowelConsonantCounter();
        vowelConsonantCounter.countVowelsAndConsonants("Hello World");
    }
}Code language: Java (java)

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 of indexOf(), 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
class CharacterOccurrenceCounter {
    public void countOccurrences(String str, char target) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == target) {
                count++;
            }
        }
        System.out.println("Occurrences of '" + target + "' = " + count);
    }
}

public class Main {
    public static void main(String[] args) {
        CharacterOccurrenceCounter characterOccurrenceCounter = new CharacterOccurrenceCounter();
        characterOccurrenceCounter.countOccurrences("programming", 'r');
    }
}Code language: Java (java)

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
class WhitespaceRemover {
    public void removeWhitespace(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c != ' ') {
                result += c;
            }
        }
        System.out.println("Result = \"" + result + "\"");
    }
}

public class Main {
    public static void main(String[] args) {
        WhitespaceRemover whitespaceRemover = new WhitespaceRemover();
        whitespaceRemover.removeWhitespace("  Hello   World  ");
    }
}Code language: Java (java)

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+" with String.matches().
▼ Solution & Explanation
class DigitOnlyChecker {
    public void checkDigitsOnly(String str) {
        boolean isDigitsOnly = !str.isEmpty();

        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                isDigitsOnly = false;
                break;
            }
        }

        System.out.println("Is Digits Only = " + isDigitsOnly);
    }
}

public class Main {
    public static void main(String[] args) {
        DigitOnlyChecker digitOnlyChecker = new DigitOnlyChecker();
        digitOnlyChecker.checkDigitsOnly("12345");
    }
}Code language: Java (java)

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
class CaseToggler {
    public void toggleCase(String str) {
        StringBuilder result = new StringBuilder();

        for (char c : str.toCharArray()) {
            if (Character.isUpperCase(c)) {
                result.append(Character.toLowerCase(c));
            } else if (Character.isLowerCase(c)) {
                result.append(Character.toUpperCase(c));
            } else {
                result.append(c);
            }
        }

        System.out.println("Result = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        CaseToggler caseToggler = new CaseToggler();
        caseToggler.toggleCase("Hello World");
    }
}Code language: Java (java)

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, though StringBuilder is 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-catch block with charAt() 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
class StringLengthCalculator {
    public void calculateLength(String str) {
        int length = 0;

        try {
            while (true) {
                str.charAt(length);
                length++;
            }
        } catch (StringIndexOutOfBoundsException e) {
            // Reached the end of the string
        }

        System.out.println("Length = " + length);
    }
}

public class Main {
    public static void main(String[] args) {
        StringLengthCalculator stringLengthCalculator = new StringLengthCalculator();
        stringLengthCalculator.calculateLength("OpenAI");
    }
}Code language: Java (java)

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 StringBuilder object to hold the combined characters.
  • Use the append() method to add characters without relying on + or concat().
  • Loop through each string’s characters individually if you want to avoid append(String) too.
  • Convert the final StringBuilder back to a String using toString().
▼ Solution & Explanation
class StringConcatenator {
    public void concatenate(String str1, String str2) {
        StringBuilder builder = new StringBuilder();

        for (char c : str1.toCharArray()) {
            builder.append(c);
        }
        for (char c : str2.toCharArray()) {
            builder.append(c);
        }

        String result = builder.toString();
        System.out.println("Result = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        StringConcatenator stringConcatenator = new StringConcatenator();
        stringConcatenator.concatenate("Hello", "World");
    }
}Code language: Java (java)

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 + and concat() 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
import java.util.Arrays;

class AnagramChecker {
    public void checkAnagram(String str1, String str2) {
        char[] arr1 = str1.toLowerCase().replace(" ", "").toCharArray();
        char[] arr2 = str2.toLowerCase().replace(" ", "").toCharArray();

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        boolean isAnagram = Arrays.equals(arr1, arr2);
        System.out.println("Is Anagram = " + isAnagram);
    }
}

public class Main {
    public static void main(String[] args) {
        AnagramChecker anagramChecker = new AnagramChecker();
        anagramChecker.checkAnagram("listen", "silent");
    }
}Code language: Java (java)

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 HashMap for 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
class WordReverser {
    public void reverseWords(String str) {
        String[] words = str.split("\\s+");
        StringBuilder result = new StringBuilder();

        for (int i = words.length - 1; i >= 0; i--) {
            result.append(words[i]);
            if (i != 0) {
                result.append(" ");
            }
        }

        System.out.println("Result = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        WordReverser wordReverser = new WordReverser();
        wordReverser.reverseWords("Java is fun");
    }
}Code language: Java (java)

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 List with Arrays.asList() and call Collections.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
import java.util.LinkedHashMap;
import java.util.Map;

class FirstNonRepeatedCharacterFinder {
    public void findFirstNonRepeatedCharacter(String str) {
        Map<Character, Integer> counts = new LinkedHashMap<>();

        for (char c : str.toCharArray()) {
            counts.put(c, counts.getOrDefault(c, 0) + 1);
        }

        char result = '\0';
        for (char c : str.toCharArray()) {
            if (counts.get(c) == 1) {
                result = c;
                break;
            }
        }

        System.out.println("First Non-Repeated Character = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        FirstNonRepeatedCharacterFinder firstNonRepeatedCharacterFinder = new FirstNonRepeatedCharacterFinder();
        firstNonRepeatedCharacterFinder.findFirstNonRepeatedCharacter("swiss");
    }
}Code language: Java (java)

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
class WordCounter {
    public void countWords(String str) {
        String trimmed = str.trim();
        int wordCount = 0;

        if (!trimmed.isEmpty()) {
            String[] words = trimmed.split("\\s+");
            wordCount = words.length;
        }

        System.out.println("Word Count = " + wordCount);
    }
}

public class Main {
    public static void main(String[] args) {
        WordCounter wordCounter = new WordCounter();
        wordCounter.countWords("  Java   is   fun  ");
    }
}Code language: Java (java)

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 Set automatically ignores duplicates, only unique characters remain.
  • Join the characters back into a single string for the final result.
▼ Solution & Explanation
import java.util.LinkedHashSet;
import java.util.Set;

class DuplicateRemover {
    public void removeDuplicates(String str) {
        Set<Character> seen = new LinkedHashSet<>();

        for (char c : str.toCharArray()) {
            seen.add(c);
        }

        StringBuilder result = new StringBuilder();
        for (char c : seen) {
            result.append(c);
        }

        System.out.println("Result = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        DuplicateRemover duplicateRemover = new DuplicateRemover();
        duplicateRemover.removeDuplicates("programming");
    }
}Code language: Java (java)

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
class StringRotationChecker {
    public void checkRotation(String str1, String str2) {
        boolean isRotation = false;

        if (str1.length() == str2.length()) {
            String doubled = str1 + str1;
            isRotation = doubled.contains(str2);
        }

        System.out.println("Is Rotation = " + isRotation);
    }
}

public class Main {
    public static void main(String[] args) {
        StringRotationChecker stringRotationChecker = new StringRotationChecker();
        stringRotationChecker.checkRotation("waterbottle", "erbottlewat");
    }
}Code language: Java (java)

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
class WordCapitalizer {
    public void capitalizeWords(String str) {
        String[] words = str.split(" ");
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (!word.isEmpty()) {
                result.append(Character.toUpperCase(word.charAt(0)));
                result.append(word.substring(1));
            }
            if (i != words.length - 1) {
                result.append(" ");
            }
        }
        System.out.println("Result = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        WordCapitalizer wordCapitalizer = new WordCapitalizer();
        wordCapitalizer.capitalizeWords("hello java world");
    }
}Code language: Java (java)

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
import java.util.LinkedHashMap;
import java.util.Map;

class HighestOccurringCharacterFinder {
    public void findHighestOccurringCharacter(String str) {
        Map<Character, Integer> counts = new LinkedHashMap<>();

        for (char c : str.toCharArray()) {
            counts.put(c, counts.getOrDefault(c, 0) + 1);
        }

        char maxChar = ' ';
        int maxCount = 0;

        for (Map.Entry<Character, Integer> entry : counts.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                maxChar = entry.getKey();
            }
        }

        System.out.println("Highest Occurring Character = " + maxChar);
    }
}

public class Main {
    public static void main(String[] args) {
        HighestOccurringCharacterFinder highestOccurringCharacterFinder = new HighestOccurringCharacterFinder();
        highestOccurringCharacterFinder.findHighestOccurringCharacter("programming");
    }
}Code language: Java (java)

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
class CustomIntegerParser {
    public void parseInt(String str) {
        int result = 0;
        boolean isNegative = false;
        int startIndex = 0;
        if (str.charAt(0) == '-') {
            isNegative = true;
            startIndex = 1;
        }
        for (int i = startIndex; i < str.length(); i++) {
            int digit = str.charAt(i) - '0';
            result = result * 10 + digit;
        }
        if (isNegative) {
            result = -result;
        }
        System.out.println("Parsed Integer = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        CustomIntegerParser customIntegerParser = new CustomIntegerParser();
        customIntegerParser.parseInt("1234");
    }
}Code language: Java (java)

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
class SubstringCounter {
    public void countOccurrences(String str, String sub) {
        int count = 0;
        int index = 0;

        while ((index = str.indexOf(sub, index)) != -1) {
            count++;
            index += sub.length();
        }

        System.out.println("Occurrences of \"" + sub + "\" = " + count);
    }
}

public class Main {
    public static void main(String[] args) {
        SubstringCounter substringCounter = new SubstringCounter();
        substringCounter.countOccurrences("abababab", "ab");
    }
}Code language: Java (java)

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, though indexOf() 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
import java.util.ArrayList;
import java.util.List;

class StringSplitter {
    public void split(String str, char delimiter) {
        List<String> parts = new ArrayList<>();
        int start = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == delimiter) {
                parts.add(str.substring(start, i));
                start = i + 1;
            }
        }
        parts.add(str.substring(start));
        for (String part : parts) {
            System.out.println(part);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        StringSplitter stringSplitter = new StringSplitter();
        stringSplitter.split("apple,banana,cherry", ',');
    }
}Code language: Java (java)

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
class StringCompressor {
    public void compress(String str) {
        StringBuilder result = new StringBuilder();
        int count = 1;
        for (int i = 1; i <= str.length(); i++) {
            if (i < str.length() && str.charAt(i) == str.charAt(i - 1)) {
                count++;
            } else {
                result.append(str.charAt(i - 1));
                result.append(count);
                count = 1;
            }
        }
        System.out.println("Result = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        StringCompressor stringCompressor = new StringCompressor();
        stringCompressor.compress("aabcccccaaa");
    }
}Code language: Java (java)

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 HashMap to 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 HashSet to 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
import java.util.HashSet;
import java.util.Set;

class LongestSubstringFinder {
    public void findLongestSubstringLength(String str) {
        Set<Character> window = new HashSet<>();
        int left = 0;
        int maxLength = 0;
        for (int right = 0; right < str.length(); right++) {
            char c = str.charAt(right);
            while (window.contains(c)) {
                window.remove(str.charAt(left));
                left++;
            }
            window.add(c);
            maxLength = Math.max(maxLength, right - left + 1);
        }
        System.out.println("Longest Substring Length = " + maxLength);
    }
}

public class Main {
    public static void main(String[] args) {
        LongestSubstringFinder longestSubstringFinder = new LongestSubstringFinder();
        longestSubstringFinder.findLongestSubstringLength("abcabcbb");
    }
}Code language: Java (java)

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
class PermutationGenerator {
    public void generate(String str) {
        permute(str, "");
    }

    private void permute(String str, String current) {
        if (current.length() == str.length()) {
            System.out.println(current);
            return;
        }
        for (int i = 0; i < str.length(); i++) {
            if (current.indexOf(str.charAt(i)) != -1) {
                continue;
            }
            permute(str, current + str.charAt(i));
        }
    }
}

public class Main {
    public static void main(String[] args) {
        PermutationGenerator permutationGenerator = new PermutationGenerator();
        permutationGenerator.generate("abc");
    }
}Code language: Java (java)

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
import java.util.Arrays;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

class AnagramGrouper {
    public void groupAnagrams(String[] words) {
        Map<String, List<String>> groups = new LinkedHashMap<>();

        for (String word : words) {
            char[] chars = word.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
        }

        for (List<String> group : groups.values()) {
            System.out.println(group);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        AnagramGrouper anagramGrouper = new AnagramGrouper();
        anagramGrouper.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"});
    }
}Code language: Java (java)

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
import java.util.ArrayDeque;
import java.util.Deque;

class ParenthesesValidator {
    public void isValid(String str) {
        Deque<Character> stack = new ArrayDeque<>();
        boolean isValid = true;

        for (char c : str.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    isValid = false;
                    break;
                }
                char top = stack.pop();
                if ((c == ')' && top != '(') ||
                    (c == '}' && top != '{') ||
                    (c == ']' && top != '[')) {
                    isValid = false;
                    break;
                }
            }
        }

        if (!stack.isEmpty()) {
            isValid = false;
        }

        System.out.println("Is Valid = " + isValid);
    }
}

public class Main {
    public static void main(String[] args) {
        ParenthesesValidator parenthesesValidator = new ParenthesesValidator();
        parenthesesValidator.isValid("{[()]}");
    }
}Code language: Java (java)

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
import java.util.HashMap;
import java.util.Map;

class RomanToIntegerConverter {
    public void convert(String str) {
        Map<Character, Integer> values = new HashMap<>();
        values.put('I', 1);
        values.put('V', 5);
        values.put('X', 10);
        values.put('L', 50);
        values.put('C', 100);
        values.put('D', 500);
        values.put('M', 1000);
        int total = 0;
        for (int i = 0; i < str.length(); i++) {
            int current = values.get(str.charAt(i));
            if (i + 1 < str.length() && current < values.get(str.charAt(i + 1))) {
                total -= current;
            } else {
                total += current;
            }
        }
        System.out.println("Integer Value = " + total);
    }
}

public class Main {
    public static void main(String[] args) {
        RomanToIntegerConverter romanToIntegerConverter = new RomanToIntegerConverter();
        romanToIntegerConverter.convert("XIV");
    }
}Code language: Java (java)

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
class LongestCommonPrefixFinder {
    public void findLongestCommonPrefix(String[] words) {
        String prefix = words.length > 0 ? words[0] : "";
        for (int i = 1; i < words.length; i++) {
            while (!words[i].startsWith(prefix)) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.isEmpty()) {
                    break;
                }
            }
        }
        System.out.println("Longest Common Prefix = " + prefix);
    }
}

public class Main {
    public static void main(String[] args) {
        LongestCommonPrefixFinder longestCommonPrefixFinder = new LongestCommonPrefixFinder();
        longestCommonPrefixFinder.findLongestCommonPrefix(new String[]{"flower", "flow", "flight"});
    }
}Code language: Java (java)

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
class CustomIndexFinder {
    public void indexOf(String str, String sub) {
        int result = -1;
        for (int i = 0; i <= str.length() - sub.length(); i++) {
            boolean match = true;
            for (int j = 0; j < sub.length(); j++) {
                if (str.charAt(i + j) != sub.charAt(j)) {
                    match = false;
                    break;
                }
            }
            if (match) {
                result = i;
                break;
            }
        }
        System.out.println("Index = " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        CustomIndexFinder customIndexFinder = new CustomIndexFinder();
        customIndexFinder.indexOf("hello world", "world");
    }
}Code language: Java (java)

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
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

class WordBreakSolver {
    public void canSegment(String str, Set<String> dictionary) {
        boolean[] dp = new boolean[str.length() + 1];
        dp[0] = true;
        for (int i = 1; i <= str.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && dictionary.contains(str.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        System.out.println("Can Be Segmented = " + dp[str.length()]);
    }
}

public class Main {
    public static void main(String[] args) {
        WordBreakSolver wordBreakSolver = new WordBreakSolver();
        Set<String> dictionary = new HashSet<>(Arrays.asList("leet", "code"));
        wordBreakSolver.canSegment("leetcode", dictionary);
    }
}Code language: Java (java)

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
class LongestPalindromicSubstringFinder {
    public void findLongestPalindromicSubstring(String str) {
        int start = 0;
        int maxLength = 1;
        for (int i = 0; i < str.length(); i++) {
            int len1 = expandAroundCenter(str, i, i);
            int len2 = expandAroundCenter(str, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > maxLength) {
                maxLength = len;
                start = i - (len - 1) / 2;
            }
        }
        System.out.println("Longest Palindromic Substring = " + str.substring(start, start + maxLength));
    }

    private int expandAroundCenter(String str, int left, int right) {
        while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }
}

public class Main {
    public static void main(String[] args) {
        LongestPalindromicSubstringFinder longestPalindromicSubstringFinder = new LongestPalindromicSubstringFinder();
        longestPalindromicSubstringFinder.findLongestPalindromicSubstring("babad");
    }
}Code language: Java (java)

Explanation:

  • expandAroundCenter(str, i, i): Checks for the longest odd-length palindrome centered at index i.
  • expandAroundCenter(str, i, i + 1): Checks for the longest even-length palindrome centered between indices i and i + 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.

Filed Under: Java Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Java Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Java Exercises
TweetF  sharein  shareP  Pin

  Java Exercises

  • All Java Exercises
  • Java Exercise for Beginners
  • Java Loops Exercise
  • Java String Exercise
  • Java ArrayList Exercise
  • Java LinkedList Exercise
  • Java HashMap and TreeMap Exercise
  • Java HashSet and TreeSet Exercise
  • Java OOP Exercise
  • Java Methods Exercise
  • Java Enums Exercise
  • Java Exception Handling Exercise
  • Java File Handling Exercise
  • Java Date and Time Exercise
  • Java Data Structures Exercise
  • Java Sorting and Searching Exercise
  • Java Lambda and Functional Interfaces Exercise
  • Java Regex Exercise
  • Java Random Data Generation Exercise
  • Java Generics Exercise
  • Java Reflection Exercise
  • Java JDBC Exercise

All Coding Exercises

Python Exercises C Exercises C++ Exercises Java Exercises C# Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com