Java
Java
Lamhot Siagian
PhD Student • AI Engineer • Software Engineer • Software Testing • Interview Preparation
[Link]
[Link]
lamhotsiagian2025@[Link]
Founder of @[Link] (Helping 130K+ people improve their skills)
Instagram: [Link]
2 Strings 13
2.1 1. Reverse a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 2. Reverse Each Word in a Sentence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 3. Find Duplicate Characters in a String . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 4. Count Occurrences of Each Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.5 5. Count Number of Words in a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.6 6. All Permutations of a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.7 7. Check Palindrome String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.8 8. Check Anagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.9 9. Count Vowels and Consonants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.10 10. Print Unique Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.11 11. Print Even Indexed Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.12 12. Remove Spaces from a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.13 13. Print Each Letter Twice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.14 14. Swap Two Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.15 15. Run-Length Encoding (aabbcccdd -> a2b2c3d2) . . . . . . . . . . . . . . . . . . . . 28
2.16 16. Separate Lowercase and Uppercase Letters . . . . . . . . . . . . . . . . . . . . . . . 29
2.17 17. Separate Alphabetic and Numeric Characters . . . . . . . . . . . . . . . . . . . . . . 30
2.18 18. Move All Zeros to the End (Digits Only) . . . . . . . . . . . . . . . . . . . . . . . . 31
2.19 19. Remove Zeros and Left-Pad with Zeros . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.20 20. Longest Substring Without Repeating Characters . . . . . . . . . . . . . . . . . . . 34
ii
CONTENTS iii
4 Java Fundamentals 50
4.1 1. Implement equals() and hashCode() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Notes 52
iv CONTENTS
Chapter 1
Example
Brute-Force Solution
Use modulo: n mod 2. Time O(1).
Best Solution
Use bitwise AND. This avoids modulo and is also O(1).
1
2 CHAPTER 1. NUMBERS & BASICS
Example
Brute-Force Solution
Try dividing by every integer from 2 to n − 1. Time O(n).
Best Solution
√ √
Only test divisors up to n (and skip even divisors after checking 2). Time O( n).
1.3. 3. FIBONACCI SERIES UP TO N TERMS 3
Example
Brute-Force Solution
Recursive definition is simple but slow: F (n) = F (n − 1) + F (n − 2) with exponential time.
3 public class P 0 3_ F i bo n a cc i _ Br u t e {
4 static long fib ( int n ) {
5 if ( n <= 1) return n ;
6 return fib ( n - 1) + fib ( n - 2) ;
7 }
8
16 }
17 System . out . println () ;
18 }
19 }
Best Solution
Iterate with two pointers. Time O(n), space O(1).
Example
Brute-Force Solution
Use a third temporary variable. Time O(1).
9 b = temp ;
10 System . out . println ( " After swapping : a=" + a + ", b=" + b);
11 }
12 }
Best Solution
Swap without a third variable using XOR (avoids overflow). Time O(1).
Example
Example: 5! = 120.
Brute-Force Solution
Recursive factorial. Time O(n), but uses stack frames.
15 }
16 }
Best Solution
Iterative factorial using BigInteger for large values. Time O(n), safer for bigger n.
Example
Brute-Force Solution
Convert to string and reverse it. Time O(k) where k is number of digits.
Best Solution
Reverse using math (mod/div). Time O(k), no string conversion.
3 public class P 0 6 _ R e v e r s e N u m b e r _ B e s t {
4 static long reverse ( long n ) {
5 long x = Math . abs ( n ) ;
6 long rev = 0;
7 while ( x > 0) {
8 rev = rev * 10 + ( x % 10) ;
9 x /= 10;
10 }
11 return n < 0 ? - rev : rev ;
12 }
13
14 public static void main ( String [] args ) {
15 Scanner sc = new Scanner ( System . in ) ;
16 System . out . print ( " Enter any number : " ) ;
17 long n = sc . nextLong () ;
18 System . out . println ( " Reverse : " + reverse ( n ) ) ;
19 }
20 }
Example
Brute-Force Solution
Convert to string, get digits, sum digitk . Time O(k).
Best Solution
Use math (no string). Precompute powers for digits 0..9. Time O(k).
Example
Brute-Force Solution
Convert to string and take length. Time O(k).
Best Solution
Count by dividing by 10. Time O(k), no string conversion.
Example
Brute-Force Solution
Convert to string and compare with reversed string. Time O(k).
3 public class P 0 9 _ P a l i n d r o m e N u m b e r _ B r u t e {
4 static boolean isPalindrome ( long n ) {
5 String s = Long . toString ( Math . abs ( n ) ) ;
6 String r = new StringBuilder ( s ) . reverse () . toString () ;
7 return s . equals ( r ) ;
8 }
9
10 public static void main ( String [] args ) {
11 Scanner sc = new Scanner ( System . in ) ;
12 System . out . print ( " Enter number : " ) ;
13 long n = sc . nextLong () ;
14 System . out . println ( isPalindrome ( n ) ? " Palindrome " : " Not Palindrome " ) ;
15 }
16 }
Best Solution
Reverse digits using math and compare. Time O(k).
19 System . out . println ( isPalindrome ( n ) ? " Palindrome " : " Not Palindrome " ) ;
20 }
21 }
Example
Brute-Force Solution
Convert to string and sum characters. Time O(k).
Best Solution
Use modulo/division. Time O(k), no string conversion.
11 return sum ;
12 }
13
14 public static void main ( String [] args ) {
15 Scanner sc = new Scanner ( System . in ) ;
16 System . out . print ( " Enter number : " ) ;
17 long n = sc . nextLong () ;
18 System . out . println ( " Sum of digits : " + sumDigits ( n ) ) ;
19 }
20 }
Chapter 2
Strings
Example
Brute-Force Solution
Build reversed string by concatenation in a loop (can be O(n2 ) due to repeated allocations).
Best Solution
Use StringBuilder which is linear time O(n).
13
14 CHAPTER 2. STRINGS
Example
Brute-Force Solution
Split by spaces, reverse each word using a nested loop. Time O(n).
1 public class S 0 2 _ R e v e r s e E a c h W o rd _ B r u t e {
2 static String reverseWord ( String w ) {
3 String r = " " ;
4 for ( int i = 0; i < w . length () ; i ++) {
5 r = w . charAt ( i ) + r ;
6 }
7 return r ;
8 }
9
10 static String reverseEachWord ( String s ) {
11 String [] words = s . split ( " " ) ;
12 String out = " " ;
13 for ( String w : words ) out += reverseWord ( w ) + " " ;
14 return out . trim () ;
15 }
16
Best Solution
Scan characters and reverse each word using a builder to avoid many string allocations.
2.3. 3. FIND DUPLICATE CHARACTERS IN A STRING 15
1 public class S 0 2 _ R e v e r s e E a c h W o r d _ B e s t {
2 static String reverseEachWord ( String s ) {
3 StringBuilder out = new StringBuilder ( s . length () ) ;
4 int i = 0;
5 while ( i < s . length () ) {
6 // copy spaces
7 while ( i < s . length () && s . charAt ( i ) == ’ ’) {
8 out . append ( ’ ’) ;
9 i ++;
10 }
11 // reverse next word
12 int start = i ;
13 while ( i < s . length () && s . charAt ( i ) != ’ ’) i ++;
14 for ( int j = i - 1; j >= start ; j - -) out . append ( s . charAt ( j ) ) ;
15 }
16 return out . toString () ;
17 }
18
19 public static void main ( String [] args ) {
20 String input = " Java is good programming languages " ;
21 System . out . println ( input ) ;
22 System . out . println ( reverseEachWord ( input ) ) ;
23 }
24 }
Example
Brute-Force Solution
For each character, count with a nested loop. Time O(n2 ).
14 int count = 0;
15 for ( int j = 0; j < s . length () ; j ++) {
16 if ( s . charAt ( j ) == c ) count ++;
17 }
18
19 if ( count > 1) {
20 System . out . println ( c + " -> " + count ) ;
21 printed . add ( c ) ;
22 }
23 }
24 }
25 }
Best Solution
Problem Statement
Given a sentence, count how many times each word appears.
Example
Brute-Force Solution
For each word, count it by scanning all words. Time O(m2 ) where m is number of words.
Best Solution
9 Map < String , Integer > count = new HashMap < >() ;
10 for ( String w : words ) {
11 count . put (w , count . getOrDefault (w , 0) + 1) ;
12 }
13
14 System . out . println ( count ) ;
15 }
16 }
18 CHAPTER 2. STRINGS
Problem Statement
Given a string, count the number of words (words are separated by spaces).
Example
Brute-Force Solution
Split by whitespace and count tokens. Time O(n) (but regex can be heavier).
1 public class S 0 5 _ C o u n t W o r d s _ B r u t e {
2 public static void main ( String [] args ) {
3 String s = " Welcome to Java World " ;
4 String [] words = s . trim () . split ( " \\ s + " ) ;
5 System . out . println ( " Number of words : " + ( s . trim () . isEmpty () ? 0 :
words . length ) ) ;
6 }
7 }
Best Solution
Scan characters and count transitions from space to non-space. Time O(n), no regex.
1 public class S 0 5_ C o un t W or d s _B e s t {
2 static int countWords ( String s ) {
3 int count = 0;
4 boolean inWord = false ;
5 for ( int i = 0; i < s . length () ; i ++) {
6 char c = s . charAt ( i ) ;
7 if ( c != ’ ’ && ! inWord ) {
8 count ++;
9 inWord = true ;
10 } else if ( c == ’ ’) {
11 inWord = false ;
12 }
13 }
14 return count ;
15 }
16
17 public static void main ( String [] args ) {
18 String s = " Welcome to Java World " ;
19 System . out . println ( " Number of words : " + countWords ( s ) ) ;
20 }
21 }
2.6. 6. ALL PERMUTATIONS OF A STRING 19
Example
Brute-Force Solution
Simple recursion using substring concatenation. Works but creates many substrings.
1 public class S 0 6 _ P e r m u t a t i o n s _ B r u t e {
2 static void permute ( String s , String prefix ) {
3 if ( s . length () == 0) {
4 System . out . println ( prefix ) ;
5 return ;
6 }
7 for ( int i = 0; i < s . length () ; i ++) {
8 String rem = s . substring (0 , i ) + s . substring ( i + 1) ;
9 permute ( rem , prefix + s . charAt ( i ) ) ;
10 }
11 }
12
13 public static void main ( String [] args ) {
14 permute ( " abc " , " " ) ;
15 }
16 }
Best Solution
Use a char array and swap in-place (avoids substring overhead).
1 public class S 0 6 _ P e r m u t a t i o n s _ B e s t {
2 static void permute ( char [] a , int idx ) {
3 if ( idx == a . length ) {
4 System . out . println ( new String ( a ) ) ;
5 return ;
6 }
7 for ( int i = idx ; i < a . length ; i ++) {
8 swap (a , idx , i ) ;
9 permute (a , idx + 1) ;
10 swap (a , idx , i ) ;
11 }
12 }
13
14 static void swap ( char [] a , int i , int j ) {
15 char t = a [ i ]; a [ i ] = a [ j ]; a [ j ] = t ;
16 }
17
18 public static void main ( String [] args ) {
20 CHAPTER 2. STRINGS
Example
Brute-Force Solution
Reverse the string and compare. Time O(n), extra space O(n).
1 public class S 0 7 _ P a l i n d r o m e S t r i n g _ B r u t e {
2 static boolean isPalindrome ( String s ) {
3 String r = new StringBuilder ( s ) . reverse () . toString () ;
4 return s . equals ( r ) ;
5 }
6
7 public static void main ( String [] args ) {
8 System . out . println ( isPalindrome ( " madam " ) ) ; // true
9 System . out . println ( isPalindrome ( " hello " ) ) ; // false
10 }
11 }
Best Solution
Two pointers from both ends. Time O(n), space O(1).
1 public class S 0 7 _ P a l i n d r o m e S t r in g _ B e s t {
2 static boolean isPalindrome ( String s ) {
3 int i = 0 , j = s . length () - 1;
4 while ( i < j ) {
5 if ( s . charAt ( i ) != s . charAt ( j ) ) return false ;
6 i ++; j - -;
7 }
8 return true ;
9 }
10
11 public static void main ( String [] args ) {
12 System . out . println ( isPalindrome ( " madam " ) ) ; // true
13 System . out . println ( isPalindrome ( " hello " ) ) ; // false
14 }
15 }
2.8. 8. CHECK ANAGRAMS 21
Example
Brute-Force Solution
Sort both strings and compare. Time O(n log n).
Best Solution
Count character frequencies (ASCII). Time O(n).
16 }
17 }
Example
Brute-Force Solution
Check each letter against a vowel list. Time O(n).
1 public class S 0 9 _ V o w e l s C o n s o n a n t s _ B r u t e {
2 static void count ( String s ) {
3 int v = 0 , c = 0;
4 s = s . toLowerCase () ;
5 for ( char ch : s . toCharArray () ) {
6 if ( ch >= ’a ’ && ch <= ’z ’) {
7 if ( ch == ’a ’ || ch == ’e ’ || ch == ’i ’ || ch == ’o ’ || ch == ’u ’) v ++;
8 else c ++;
9 }
10 }
11 System . out . println ( " Vowels : " + v ) ;
12 System . out . println ( " Consonants : " + c ) ;
13 }
14
15 public static void main ( String [] args ) {
16 count ( " Hello World " ) ;
17 }
18 }
Best Solution
Same one-pass scan; just written cleanly with a helper for readability. Time O(n).
1 public class S 0 9 _ V o w e l s C o n s o n a nt s _ B e s t {
2 static boolean isVowel ( char ch ) {
3 return ch == ’a ’ || ch == ’e ’ || ch == ’i ’ || ch == ’o ’ || ch == ’u ’;
4 }
5
6 static void count ( String s ) {
7 int v = 0 , c = 0;
8 s = s . toLowerCase () ;
9 for ( int i = 0; i < s . length () ; i ++) {
10 char ch = s . charAt ( i ) ;
2.10. 10. PRINT UNIQUE CHARACTERS 23
Example
Brute-Force Solution
For each char, check whether it appeared earlier (nested loop). Time O(n2 ).
1 public class S 1 0 _ U n i q u e C h a r s _ B r u t e {
2 static void printUnique ( String s ) {
3 for ( int i = 0; i < s . length () ; i ++) {
4 char c = s . charAt ( i ) ;
5 boolean seenBefore = false ;
6 for ( int j = 0; j < i ; j ++) {
7 if ( s . charAt ( j ) == c ) { seenBefore = true ; break ; }
8 }
9 if (! seenBefore ) System . out . print ( c + " " ) ;
10 }
11 System . out . println () ;
12 }
13
14 public static void main ( String [] args ) {
15 printUnique ( " Java Automation " ) ;
16 }
17 }
Best Solution
Use a boolean array (ASCII). Time O(n).
1 public class S 1 0 _ U n i q u e C h a r s _ B e s t {
2 static void printUnique ( String s ) {
24 CHAPTER 2. STRINGS
Example
Brute-Force Solution
Loop all indices and check i mod 2 == 0. Time O(n).
1 public class S 1 1 _ E v e n I n d e x e d _ B r u t e {
2 public static void main ( String [] args ) {
3 String s = " Automation " ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 if ( i % 2 == 0) System . out . print ( s . charAt ( i ) ) ;
6 }
7 System . out . println () ;
8 }
9 }
Best Solution
Step by 2 directly. Time O(n) but fewer operations.
1 public class S 1 1 _ E v e n I n d e x e d _ B e s t {
2 public static void main ( String [] args ) {
3 String s = " Automation " ;
4 for ( int i = 0; i < s . length () ; i += 2) {
5 System . out . print ( s . charAt ( i ) ) ;
6 }
2.12. 12. REMOVE SPACES FROM A STRING 25
Problem Statement
Given a string, remove all space characters.
Example
Brute-Force Solution
1 public class S 1 2 _ R e m o v e S p a c e s _ B r u t e {
2 public static void main ( String [] args ) {
3 String s = " Welcome to Java World " ;
4 System . out . println ( s . replaceAll ( " \\ s + " , " " ) ) ;
5 }
6 }
Best Solution
1 public class S 1 2 _ R e m o v e S p a c e s _ B e s t {
2 static String removeSpaces ( String s ) {
3 StringBuilder out = new StringBuilder ( s . length () ) ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 char c = s . charAt ( i ) ;
6 if ( c != ’ ’) out . append ( c ) ;
7 }
8 return out . toString () ;
9 }
10
11 public static void main ( String [] args ) {
12 String s = " Welcome to Java World " ;
13 System . out . println ( removeSpaces ( s ) ) ;
14 }
15 }
26 CHAPTER 2. STRINGS
Problem Statement
Given a string, output a new string where each character is repeated twice (hello → hheelllloo).
Example
Brute-Force Solution
1 public class S 1 3 _ D o u b l e C h a r s _ B r u t e {
2 static String doubleChars ( String s ) {
3 String out = " " ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 out += " " + s . charAt ( i ) + s . charAt ( i ) ;
6 }
7 return out ;
8 }
9
10 public static void main ( String [] args ) {
11 System . out . println ( doubleChars ( " hello " ) ) ;
12 }
13 }
Best Solution
1 public class S 1 3 _ D o u b l e C h a r s _ B e s t {
2 static String doubleChars ( String s ) {
3 StringBuilder out = new StringBuilder ( s . length () * 2) ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 char c = s . charAt ( i ) ;
6 out . append ( c ) . append ( c ) ;
7 }
8 return out . toString () ;
9 }
10
11 public static void main ( String [] args ) {
12 System . out . println ( doubleChars ( " hello " ) ) ;
13 }
14 }
2.14. 14. SWAP TWO STRINGS 27
Problem Statement
Swap two strings str1 and str2.
Example
Brute-Force Solution
1 public class S 1 4 _ S w a p S t r i n g s _ B r u t e {
2 public static void main ( String [] args ) {
3 String str1 = " Hello " ;
4 String str2 = " World " ;
5
6 System . out . println ( " Before : str1 = " + str1 + " , str2 = " + str2 ) ;
7 String temp = str1 ;
8 str1 = str2 ;
9 str2 = temp ;
10 System . out . println ( " After : str1 = " + str1 + " , str2 = " + str2 ) ;
11 }
12 }
Best Solution
Swap without a third variable by concatenation + substring. Time O(n) due to string copies.
1 public class S 1 4 _ S w a p S t r i n g s _ B e s t {
2 public static void main ( String [] args ) {
3 String str1 = " Hello " ;
4 String str2 = " World " ;
5
6 System . out . println ( " Before : str1 = " + str1 + " , str2 = " + str2 ) ;
7
8 str1 = str1 + str2 ; // " HelloWorld "
9 str2 = str1 . substring (0 , str1 . length () - str2 . length () ) ; // " Hello "
10 str1 = str1 . substring ( str2 . length () ) ; // " World "
11
12 System . out . println ( " After : str1 = " + str1 + " , str2 = " + str2 ) ;
13 }
14 }
28 CHAPTER 2. STRINGS
Example
Brute-Force Solution
Brute-force by counting each character’s run with nested checks (or repeatedly scanning).
Best Solution
One pass with StringBuilder. Time O(n).
14 }
15 return out . toString () ;
16 }
17
18 public static void main ( String [] args ) {
19 System . out . println ( encode ( " aabbcccdd " ) ) ;
20 }
21 }
Problem Statement
Given a string, output two strings: (1) all lowercase letters, (2) all uppercase letters.
Example
Brute-Force Solution
Two passes: first collect lowercase, then uppercase. Time O(n).
1 public class S 1 6 _ S e p a r a t e C a s e _ B r u t e {
2 static String lowerOnly ( String s ) {
3 String out = " " ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 char c = s . charAt ( i ) ;
6 if ( Character . isLowerCase ( c ) ) out += c ;
7 }
8 return out ;
9 }
10
Best Solution
One pass with two builders. Time O(n), fewer allocations.
1 public class S 1 6 _ S e p a r a t e C a s e _ B e s t {
2 static void separate ( String s ) {
3 StringBuilder lower = new StringBuilder () ;
4 StringBuilder upper = new StringBuilder () ;
5
6 for ( int i = 0; i < s . length () ; i ++) {
7 char c = s . charAt ( i ) ;
8 if ( Character . isLowerCase ( c ) ) lower . append ( c ) ;
9 else if ( Character . isUpperCase ( c ) ) upper . append ( c ) ;
10 }
11
12 System . out . println ( " Lowercase : " + lower ) ;
13 System . out . println ( " Uppercase : " + upper ) ;
14 }
15
16 public static void main ( String [] args ) {
17 separate ( " aBACbcEDed " ) ;
18 }
19 }
Example
Brute-Force Solution
Use two passes: one for letters, one for digits. Time O(n).
1 public class S 1 7 _ S e p a r a t e A l p h a N u m e r i c _ B r u t e {
2 static String letters ( String s ) {
3 String out = " " ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 char c = s . charAt ( i ) ;
6 if ( Character . isLetter ( c ) ) out += c ;
7 }
8 return out ;
9 }
10
11 static String digits ( String s ) {
12 String out = " " ;
13 for ( int i = 0; i < s . length () ; i ++) {
14 char c = s . charAt ( i ) ;
2.18. 18. MOVE ALL ZEROS TO THE END (DIGITS ONLY) 31
Best Solution
One pass using two builders. Time O(n).
1 public class S 1 7 _ S e p a r a t e A l p h a N u m e r i c _ B e s t {
2 static void separate ( String s ) {
3 StringBuilder alpha = new StringBuilder () ;
4 StringBuilder numeric = new StringBuilder () ;
5 for ( int i = 0; i < s . length () ; i ++) {
6 char c = s . charAt ( i ) ;
7 if ( Character . isLetter ( c ) ) alpha . append ( c ) ;
8 else if ( Character . isDigit ( c ) ) numeric . append ( c ) ;
9 }
10 System . out . println ( " Alpha : " + alpha ) ;
11 System . out . println ( " Numeric : " + numeric ) ;
12 }
13
Example
32400121200 -> 32412120000.
Brute-Force Solution
Brute-force by repeatedly swapping adjacent zeros to the right (bubble-like). Time O(n2 ).
1 public class S 1 8 _ M o v e Z e r o s E n d _ B r u t e {
32 CHAPTER 2. STRINGS
Best Solution
Stable partition in one pass: build non-zeros then append zeros. Time O(n).
1 public class S 1 8 _ M o v e Z e r o s E n d _ B e s t {
2 static String moveZeros ( String s ) {
3 StringBuilder nonZero = new StringBuilder ( s . length () ) ;
4 int zeros = 0;
5
6 for ( int i = 0; i < s . length () ; i ++) {
7 char c = s . charAt ( i ) ;
8 if ( c == ’0 ’) zeros ++;
9 else nonZero . append ( c ) ;
10 }
11 for ( int i = 0; i < zeros ; i ++) nonZero . append ( ’0 ’) ;
12 return nonZero . toString () ;
13 }
14
15 public static void main ( String [] args ) {
16 System . out . println ( moveZeros ( " 32400121200 " ) ) ; // 32412120000
17 }
18 }
Problem Statement
Given a digit string 32400121200, remove all internal zeros to form 3241212, then left-pad with
zeros to match the original length, producing 00003241212.
2.19. 19. REMOVE ZEROS AND LEFT-PAD WITH ZEROS 33
Example
32400121200 -> 00003241212.
Brute-Force Solution
1 public class S 1 9 _ R e m o v e Z e r o s P a d L e f t _ B r u t e {
2 static String transform ( String s ) {
3 String noZeros = " " ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 char c = s . charAt ( i ) ;
6 if ( c != ’0 ’) noZeros += c ; // can be O ( n ^2) due to concatenation
7 }
8 while ( noZeros . length () < s . length () ) {
9 noZeros = " 0 " + noZeros ;
10 }
11 return noZeros ;
12 }
13
14 public static void main ( String [] args ) {
15 System . out . println ( transform ( " 32400121200 " ) ) ; // 00003241212
16 }
17 }
Best Solution
1 public class S 1 9 _ R e m o v e Z e r o s P a d L e f t _ B e s t {
2 static String transform ( String s ) {
3 StringBuilder digits = new StringBuilder ( s . length () ) ;
4 for ( int i = 0; i < s . length () ; i ++) {
5 char c = s . charAt ( i ) ;
6 if ( c != ’0 ’) digits . append ( c ) ;
7 }
8
9 int pad = s . length () - digits . length () ;
10 StringBuilder out = new StringBuilder ( s . length () ) ;
11 for ( int i = 0; i < pad ; i ++) out . append ( ’0 ’) ;
12 out . append ( digits ) ;
13 return out . toString () ;
14 }
15
16 public static void main ( String [] args ) {
17 System . out . println ( transform ( " 32400121200 " ) ) ; // 00003241212
18 }
19 }
34 CHAPTER 2. STRINGS
Example
Brute-Force Solution
Try every start index and extend until a repeat occurs. Worst-case O(n2 ).
3 public class S 2 0 _ L o n g e s t U n i q u e S u b s t r i n g _ B r u t e {
4 static int l e n g t h O f L o n g e s t S u b s t r i n g ( String s ) {
5 int best = 0;
6 for ( int i = 0; i < s . length () ; i ++) {
7 HashSet < Character > seen = new HashSet < >() ;
8 for ( int j = i ; j < s . length () ; j ++) {
9 char c = s . charAt ( j ) ;
10 if ( seen . contains ( c ) ) break ;
11 seen . add ( c ) ;
12 best = Math . max ( best , j - i + 1) ;
13 }
14 }
15 return best ;
16 }
17
18 public static void main ( String [] args ) {
19 System . out . println ( l e n g t h O f L o n g e s t S u b s t r i n g ( " abcabcbb " ) ) ; // 3
20 System . out . println ( l e n g t h O f L o n g e s t S u b s t r i n g ( " bbbbb " ) ) ; // 1
21 System . out . println ( l e n g t h O f L o n g e s t S u b s t r i n g ( " pwwkew " ) ) ; // 3
22 System . out . println ( l e n g t h O f L o n g e s t S u b s t r i n g ( " " ) ) ; // 0
23 }
24 }
Best Solution
Sliding window with last-seen index. Time O(n).
Problem Statement
Given two integer arrays, return the set of common elements.
Example
Brute-Force Solution
Brute-force: for each element in array1, scan array2. Time O(nm).
36
3.2. 2. FIND FIRST AND LAST ELEMENT OF AN ARRAYLIST 37
Best Solution
Best: put one array in a set, then scan the other. Time O(n + m).
Example
Output: First element: Apple; Last element: Elderberry (per PDF example).
Brute-Force Solution
Brute-force: loop to the last element. Time O(n).
Best Solution
Best: direct indexing with size()-1. Time O(1).
Example
Brute-Force Solution
Bubble sort. Time O(n2 ).
5 if ( a [ i ] > a [ i + 1]) {
6 int t = a [ i ]; a [ i ] = a [ i + 1]; a [ i + 1] = t ;
7 }
8 }
9 }
10 }
11
Best Solution
Problem Statement
Given an integer array, remove duplicates.
Example
Brute-Force Solution
Brute-force: nested loop and build a unique list manually. Time O(n2 ).
Best Solution
Best: use LinkedHashSet to preserve insertion order. Time O(n).
Example
Brute-Force Solution
Brute-force: nested loops. Time O(n2 ).
3 public class A 0 5 _ R e m o v e D u p L i s t _ B r u t e {
4 static ArrayList < Integer > unique ( ArrayList < Integer > list ) {
5 ArrayList < Integer > res = new ArrayList < >() ;
6 for ( int x : list ) {
7 boolean exists = false ;
8 for ( int y : res ) {
9 if ( x == y ) { exists = true ; break ; }
10 }
11 if (! exists ) res . add ( x ) ;
12 }
13 return res ;
14 }
15
16 public static void main ( String [] args ) {
17 ArrayList < Integer > list = new ArrayList < >() ;
18 int [] a = {5 ,2 ,9 ,1 ,6 ,2 ,5};
19 for ( int x : a ) list . add ( x ) ;
20
Best Solution
Best: LinkedHashSet keeps insertion order. Time O(n).
7 Set < Integer > set = new LinkedHashSet < >( list ) ;
8 return new ArrayList < >( set ) ;
9 }
10
11 public static void main ( String [] args ) {
12 ArrayList < Integer > list = new ArrayList < >() ;
13 int [] a = {5 ,2 ,9 ,1 ,6 ,2 ,5};
14 for ( int x : a ) list . add ( x ) ;
15
16 System . out . println ( unique ( list ) ) ;
17 }
18 }
Example
Brute-Force Solution
Brute-force: for each number 1..n, scan array to see if present. Time O(n2 ).
1 public class A 0 6 _ M i s s i n g N u m b e r _ B r u t e {
2 static int missing ( int [] a ) {
3 int n = a . length + 1;
4 for ( int x = 1; x <= n ; x ++) {
5 boolean found = false ;
6 for ( int v : a ) {
7 if ( v == x ) { found = true ; break ; }
8 }
9 if (! found ) return x ;
10 }
11 return -1;
12 }
13
14 public static void main ( String [] args ) {
15 int [] a = {1 ,2 ,4 ,5 ,6};
16 System . out . println ( missing ( a ) ) ; // 3
17 }
18 }
Best Solution
Best: sum formula (or XOR). Time O(n).
3.7. 7. FIND LARGEST AND SMALLEST ELEMENT IN AN ARRAY 43
1 public class A 0 6 _ M i s s i n g N u m b e r _ B e s t {
2 static int missing ( int [] a ) {
3 int n = a . length + 1;
4 long total = ( long ) n * ( n + 1) / 2;
5 long sum = 0;
6 for ( int v : a ) sum += v ;
7 return ( int ) ( total - sum ) ;
8 }
9
10 public static void main ( String [] args ) {
11 int [] a = {1 ,2 ,4 ,5 ,6};
12 System . out . println ( missing ( a ) ) ; // 3
13 }
14 }
Example
Smallest=1, Largest=9.
Brute-Force Solution
Brute-force: sort the array and take first/last. Time O(n log n).
Best Solution
Best: one pass. Time O(n), space O(1).
44 CHAPTER 3. ARRAYS & COLLECTIONS
Example
Brute-Force Solution
Linear search. Time O(n).
Best Solution
If the array is sorted, use binary search. Time O(log n).
3.9. 9. SUM ONLY INTEGERS IN A MIXED STRING ARRAY 45
Example
Brute-Force Solution
Brute-force: check each string with a regex before parsing. Time O(nk).
1 public class A 0 9 _ S u m I n t e g e r s _ B r u t e {
2 static boolean isInteger ( String s ) {
3 return s . matches ( " -?\\ d + " ) ;
4 }
5
6 static int sum ( String [] a ) {
7 int sum = 0;
8 for ( String x : a ) {
9 if ( isInteger ( x ) ) sum += Integer . parseInt ( x ) ;
10 }
11 return sum ;
12 }
13
14 public static void main ( String [] args ) {
15 String [] a = { " 5 " ," 2 " ," 9 " ," a " ," 1 " ," 6 " ," # " ," 3 " };
46 CHAPTER 3. ARRAYS & COLLECTIONS
Best Solution
Best: try/catch parsing (simple and common in interviews).
1 public class A 0 9 _ S u m I n t e g e r s _ B e s t {
2 static int sum ( String [] a ) {
3 int sum = 0;
4 for ( String x : a ) {
5 try {
6 sum += Integer . parseInt ( x ) ;
7 } catch ( N u m b e r F o r m a t E x c e p t i o n ignored ) {
8 // ignore non - integers
9 }
10 }
11 return sum ;
12 }
13
14 public static void main ( String [] args ) {
15 String [] a = { " 5 " ," 2 " ," 9 " ," a " ," 1 " ," 6 " ," # " ," 3 " };
16 System . out . println ( sum ( a ) ) ; // 26
17 }
18 }
Example
Minimum=1, Maximum=9.
Brute-Force Solution
Brute-force: sort and take ends. Time O(n log n).
10 }
Best Solution
Best: one pass. Time O(n).
Example
Brute-Force Solution
Use modulo check. Time O(n).
1 public class A 1 1 _ C o u n t O d d E v e n _ B r u t e {
2 static int [] count ( int [] a ) {
3 int odd = 0 , even = 0;
4 for ( int x : a ) {
5 if ( x % 2 == 0) even ++;
6 else odd ++;
7 }
8 return new int []{ odd , even };
9 }
10
48 CHAPTER 3. ARRAYS & COLLECTIONS
Best Solution
Use bitwise AND to check parity. Time O(n).
1 public class A 1 1 _ C o u n t O d d E v e n _ B e s t {
2 static int [] count ( int [] a ) {
3 int odd = 0 , even = 0;
4 for ( int x : a ) {
5 if ( ( x & 1) == 0 ) even ++;
6 else odd ++;
7 }
8 return new int []{ odd , even };
9 }
10
11 public static void main ( String [] args ) {
12 int [] a = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9};
13 int [] r = count ( a ) ;
14 System . out . println ( " Odd : " + r [0]) ;
15 System . out . println ( " Even : " + r [1]) ;
16 }
17 }
Example
Brute-Force Solution
Brute-force: for each element count occurrences with a nested loop. Time O(n2 ).
Best Solution
Best: count with a HashMap. Time O(n).
Java Fundamentals
Example
Brute-Force Solution
Brute-force (wrong approach): rely on default [Link], which compares references.
50
4.1. 1. IMPLEMENT EQUALS() AND HASHCODE() 51
Best Solution
Best: override both methods using all identity fields.
• All code snippets are standalone Java classes. Copy a snippet into a file named exactly as its public
class to compile and run.
• Brute-force solutions favor simplicity and directness. Best solutions favor efficiency and clean
implementation.
52