0% found this document useful (0 votes)
1 views31 pages

java_dsa1 (1)

Uploaded by

saigudipati9000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views31 pages

java_dsa1 (1)

Uploaded by

saigudipati9000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Java Solutions to Al-

gorithmic Problems
August 1, 2025

1
1 String Manipulation Problems

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗IsSubsequenceT hismethodchecksif stringsisasubsequenc


1 import java . util . HashSet ;
2 import java . util . Set ;
3

4 class Solution {
5 public static boolean isSubsequence ( String s , String t ) {
6 int i =0 , j =0;
7 int n1 = s . length () , n2 = t . length () ;
8 while (i < n1 && j < n2 ) {
9 if ( s . charAt ( i ) == t . charAt ( j ) ) {
10 i ++;
11 }
12 j ++;
13 }
14 return i == n1 ;
15 }
16 }

Listing 1: Check if a string is a subsequence

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ReverseW ordsinaStringT hismethodreverseseachwor


1 class Solution {
2 public static String reverseWords ( String s ) {
3 if ( s == null || s . length () ==0) {
4 return s ;
5 }
6 String str [] = s . split ( " \\ s + " ) ;
7 StringBuilder sb = null ;
8 StringBuilder res = new StringBuilder () ;
9 for ( String word : str ) {
10 sb = new StringBuilder ( word ) ;
11 sb . reverse () ;
12 res . append ( sb ) . append ( " " ) ;
13 }
14 int n = res . length () ;
15 res = res . replace (n -1 , n , " " ) ;
16 return res . toString () ;
17 }
18

19 public static void main ( String [] args ) {


20 String s2 = " Let ’s take LeetCode contest " ;
21 System . out . println ( reverseWords ( s2 ) ) ;
22 }
23 }

Listing 2: Reverse each word in a string

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗IsAcronymT hismethodchecksif astringsisanacronym


1 import java . util . List ;
2

3 class Solution {
4 public boolean isAcronym ( List < String > words , String s ) {
5 String res = " " ;
6 for ( String i : words ) {
7 res = res + i . charAt (0) ;
8 }
9 return s . equals ( res ) ;
10 }

2
11 }

Listing 3: Check if a string is an acronym of words

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗RansomN oteT hismethodchecksif aransomnotecanbec


1 class Solution {
2 public static boolean canConstruct ( String ransomNote , String magazine ) {
3 if ( ransomNote . length () > magazine . length () ) {
4 return false ;
5 }
6 int [] freq = new int [26];
7 for ( char c : magazine . toCharArray () ) {
8 freq [ c - ’a ’ ]++;
9 }
10 for ( char c : ransomNote . toCharArray () ) {
11 if ( freq [ c - ’a ’] == 0) {
12 return false ;
13 }
14 freq [ c - ’a ’] - -;
15 }
16 return true ;
17 }
18

19 public static void main ( String [] args ) {


20 String a = " aa " ;
21 String b = " ab " ;
22 System . out . println ( canConstruct (a , b ) ) ;
23 }
24 }

Listing 4: Check if ransom note can be constructed from magazine

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗LargestOddN umberT hismethodf indsthelargestoddnu


1 class Solution {
2 public static String largestOddNumber ( String num ) {
3 String ans = " " ;
4 int n = num . length () ;
5 for ( int i = n - 1; i >= 0; i - -) {
6 int c = num . charAt ( i ) - ’0 ’;
7 if ( c % 2 != 0) {
8 return num . substring (0 , i + 1) ;
9 }
10 }
11 return ans ;
12 }
13

14 public static void main ( String [] args ) {


15 String s = " 378526 " ;
16 System . out . println ( largestOddNumber ( s ) ) ;
17 }
18 }

Listing 5: Find largest odd number from string

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗LongestCommonP ref ixT hismethodf indsthelongestco


1 class Solution {
2 public static String longestCommonPrefix ( String [] strs ) {
3 if ( strs == null || strs . length == 0) return " " ;
4 String prefix = strs [0];
5 for ( int i = 1; i < strs . length ; i ++) {
6 while ( strs [ i ]. indexOf ( prefix ) != 0) {
7 prefix = prefix . substring (0 , prefix . length () - 1) ;

3
8 if ( prefix . isEmpty () ) return " " ;
9 }
10 }
11 return prefix ;
12 }
13

14 public static void main ( String [] args ) {


15 String [] strs = { " flower " , " flow " , " flight " };
16 System . out . println ( longestCommonPrefix ( strs ) ) ;
17 }
18 }

Listing 6: Find longest common prefix of strings

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗RotateStringT hismethodchecksif onestringcanberotat


1 class Solution {
2 public static boolean rotateString ( String s , String goal ) {
3 if ( s . length () != goal . length () ) {
4 return false ;
5 }
6 return ( s + s ) . contains ( goal ) ;
7 }
8

9 public static void main ( String [] args ) {


10 System . out . println ( rotateString ( " abcde " , " cdeab " ) ) ;
11 }
12 }

Listing 7: Check if a string can be rotated to match another

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ReverseW ords(OrderReversal)T hismethodreversesth


1 class Solution {
2 public static String reverseWords ( String s ) {
3 StringBuffer sb = new StringBuffer () ;
4 s = s . trim () ;
5 String strs [] = s . split ( " \\ s + " ) ;
6 for ( int i = strs . length - 1; i >= 0; i - -) {
7 sb . append ( strs [ i ]) . append ( " " ) ;
8 }
9 return sb . toString () . trim () ;
10 }
11

12 public static void main ( String [] args ) {


13 System . out . println ( reverseWords ( " hello world "));
14 }
15 }

Listing 8: Reverse the order of words in a string

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F requencySortT hismethodsortscharactersinastringby


1 import java . util . Map ;
2 import java . util . TreeMap ;
3

4 class Solution {
5 public static String frequencySort ( String s ) {
6 String ans = " " ;
7 Map < Character , Integer > tmap = new TreeMap < >() ;
8 for ( char c : s . toCharArray () ) {
9 tmap . put (c , tmap . getOrDefault (c , 0) + 1) ;
10 }
11 for ( Map . Entry < Character , Integer > ent : tmap . entrySet () ) {
12 char key = ent . getKey () ;

4
13 int val = ent . getValue () ;
14 for ( int i = 0; i < val ; i ++) {
15 ans += key ;
16 }
17 }
18 return ans ;
19 }
20

21 public static void main ( String [] args ) {


22 System . out . println ( frequencySort ( " Aabb " ) ) ;
23 }
24 }

Listing 9: Sort characters by frequency

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗CompressStringT hismethodcompressesacharacterarr


1 class Solution {
2 public static int compress ( char [] chars ) {
3 int write = 0 , anchor = 0;
4 for ( int read = 0; read < chars . length ; read ++) {
5 if ( read + 1 == chars . length || chars [ read + 1] != chars [ read ]) {
6 chars [ write ++] = chars [ read ];
7 if ( read > anchor ) {
8 String count = String . valueOf ( read - anchor + 1) ;
9 for ( char c : count . toCharArray () ) {
10 chars [ write ++] = c ;
11 }
12 }
13 anchor = read + 1;
14 }
15 }
16 return write ;
17 }
18

19 public static void main ( String [] args ) {


20 char chars [] = { ’a ’ , ’a ’ , ’b ’ , ’b ’ , ’c ’ , ’c ’ , ’c ’ , ’a ’ };
21 System . out . println ( compress ( chars ) ) ;
22 }
23 }

Listing 10: Compress a character array

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗W ordP atternT hismethodchecksif apatternmatchesas


1 import java . util . HashMap ;
2 import java . util . HashSet ;
3 import java . util . Map ;
4 import java . util . Set ;
5

6 class Solution {
7 public static boolean wordPattern ( String pattern , String s ) {
8 s = s . trim () ;
9 String arr [] = s . split ( " \\ s + " ) ;
10 if ( pattern . length () != arr . length ) {
11 return false ;
12 }
13 Map < Character , String > hmap = new HashMap < >() ;
14 Set < String > set = new HashSet < >() ;
15 int i = 0;
16 for ( char c : pattern . toCharArray () ) {
17 String val = arr [ i ++];
18 String str = hmap . getOrDefault (c , " " ) ;
19 if ( val . equals ( str ) ) {

5
20 continue ;
21 } else if ( str . equals ( " " ) ) {
22 if ( set . contains ( val ) ) {
23 return false ;
24 }
25 hmap . put (c , val ) ;
26 set . add ( val ) ;
27 } else {
28 return false ;
29 }
30 }
31 return true ;
32 }
33

34 public static void main ( String [] args ) {


35 String pat = " abba " , s = " dog cat cat fish " ;
36 System . out . println ( wordPattern ( pat , s ) ) ;
37 }
38 }

Listing 11: Check if a pattern matches a string

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F irstU niqueCharacterT hismethodf indstheindexof th


1 import java . util . LinkedHashMap ;
2 import java . util . Map ;
3

4 class Solution {
5 public static int firstUniqChar ( String s ) {
6 Map < Character , Integer > hmap = new LinkedHashMap < >() ;
7 for ( char c : s . toCharArray () ) {
8 hmap . put (c , hmap . getOrDefault (c , 0) + 1) ;
9 }
10 char ch = ’ ’;
11 for ( char c : hmap . keySet () ) {
12 if ( hmap . get ( c ) == 1) {
13 ch = c ;
14 break ;
15 }
16 }
17 for ( int i = 0; i < s . length () ; i ++) {
18 if ( s . charAt ( i ) == ch ) {
19 return i ;
20 }
21 }
22 return -1;
23 }
24

25 public static void main ( String [] args ) {


26 System . out . println ( firstUniqChar ( " leetcode " ) ) ;
27 }
28 }

Listing 12: Find first unique character in a string

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F indtheDif f erenceT hismethodf indstheextracharacte


1 import java . util . LinkedHashMap ;
2 import java . util . Map ;
3

4 class Solution {
5 public static char findTheDifference ( String s , String t ) {
6 Map < Character , Integer > hmap = new LinkedHashMap < >() ;
7 for ( char c : s . toCharArray () ) {

6
8 hmap . put (c , hmap . getOrDefault (c , 0) + 1) ;
9 }
10 for ( char c : t . toCharArray () ) {
11 hmap . put (c , hmap . getOrDefault (c , 0) + 1) ;
12 }
13 for ( char c : hmap . keySet () ) {
14 if ( hmap . get ( c ) % 2 == 1) {
15 return c ;
16 }
17 }
18 return ’0 ’;
19 }
20

21 public static void main ( String [] args ) {


22 System . out . println ( findTheDifference ( " " , " y " ) ) ;
23 }
24 }
Listing 13: Find extra character in string
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗CountSegmentsT hismethodcountsthenumberof segme
1 class Solution {
2 public static int countSegments ( String s ) {
3 String [] arr = s . trim () . split ( " \\ s + " ) ;
4 return s . isEmpty () ? 0 : arr . length ;
5 }
6

7 public static void main ( String [] args ) {


8 System . out . println ( countSegments ( " Hello , my name is John " ) ) ;
9 }
10 }
Listing 14: Count segments in a string
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗DetectCapitalU seT hismethodchecksif aword′ scapitali
1 class Solution {
2 public static boolean isCap ( char ch []) {
3 int count = 0;
4 for ( char i : ch ) {
5 if ( i >= ’A ’ && i <= ’Z ’) {
6 count ++;
7 }
8 }
9 return count == 1 && Character . isUpperCase ( ch [0]) ;
10 }
11

12 public static boolean detectCapitalUse ( String word ) {


13 if ( word . length () == 1) {
14 return true ;
15 }
16 return word . toUpperCase () . equals ( word ) ||
17 word . toLowerCase () . equals ( word ) ||
18 isCap ( word . toCharArray () ) ;
19 }
20

21 public static void main ( String [] args ) {


22 System . out . println ( detectCapitalUse ( " flaG " ) ) ;
23 }
24 }
Listing 15: Check valid capitalization in a word
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ReverseStringwithkSegmentsT hismethodreverseseve

7
1 class Solution {
2 public static void rev ( char ch [] , int s , int end ) {
3 if ( s > end ) {
4 return ;
5 }
6 char temp = ch [ s ];
7 ch [ s ] = ch [ end ];
8 ch [ end ] = temp ;
9 s ++;
10 end - -;
11 rev ( ch , s , end ) ;
12 }
13

14 public static String reverseStr ( String s , int k ) {


15 char ch [] = s . toCharArray () ;
16 int n = ch . length ;
17 for ( int i = 0; i < n ; i += 2 * k ) {
18 int start = i ;
19 int end = Math . min ( i + k - 1 , n - 1) ;
20 rev ( ch , start , end ) ;
21 }
22 return new String ( ch ) ;
23 }
24

25 public static void main ( String [] args ) {


26 String s = " abcd " ;
27 int k = 2;
28 System . out . println ( reverseStr (s , k ) ) ;
29 }
30 }

Listing 16: Reverse every k characters in a string

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗Scoreof StringT hismethodcalculatesthesumof absolut


1 class Solution {
2 public static int scoreOfString ( String s ) {
3 int count = 0;
4 char ch [] = s . toCharArray () ;
5 int n = ch . length ;
6 for ( int i = 0; i < n - 1; i ++) {
7 count = count + Math . abs ( ch [ i ] - ch [ i + 1]) ;
8 }
9 return count ;
10 }
11

12 public static void main ( String [] args ) {


13 System . out . println ( scoreOfString ( " hello " ) ) ;
14 }
15 }

Listing 17: Calculate score of a string

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F inalV alueAf terOperationsT hismethodcalculatesthe


1 class Solution {
2 public static int f i n a l V a l u e Af t e r O p e r a t i o n s ( String [] operations ) {
3 int x = 0;
4 for ( String i : operations ) {
5 if ( i . equals ( " X ++ " ) || i . equals ( " ++ X " ) ) {
6 x ++;
7 } else {
8 x - -;

8
9 }
10 }
11 return x ;
12 }
13

14 public static void main ( String [] args ) {


15 String [] arr = { " ++ X " , " ++ X " , " X ++ " };
16 System . out . println ( f i n a l V a l u e A ft e r O p e r a t i o n s ( arr ) ) ;
17 }
18 }
Listing 18: Calculate final value after operations
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗W ordsContainingCharacterT hismethodf indsindiceso
1 import java . util . ArrayList ;
2 import java . util . List ;
3

4 class Solution {
5 public static List < Integer > findWordsContaining ( String [] words , char x ) {
6 List < Integer > list = new ArrayList < >() ;
7 int i = 0;
8 for ( String word : words ) {
9 if ( word . indexOf ( x ) != -1) {
10 list . add ( i ) ;
11 }
12 i ++;
13 }
14 return list ;
15 }
16

17 public static void main ( String [] args ) {


18 String [] arr = { " leet " , " code " };
19 char c = ’e ’;
20 System . out . println ( findWordsContaining ( arr , c ) ) ;
21 }
22 }
Listing 19: Find words containing a specific character
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ArrayStringsAreEqualT hismethodchecksif twoarray
1 class Solution {
2 public static boolean arrayStringsAreEqual ( String [] word1 , String [] word2 ) {
3 StringBuilder sb1 = new StringBuilder () ;
4 StringBuilder sb2 = new StringBuilder () ;
5 for ( String i : word1 ) {
6 sb1 . append ( i ) ;
7 }
8 for ( String i : word2 ) {
9 sb2 . append ( i ) ;
10 }
11 return sb1 . toString () . equals ( sb2 . toString () ) ;
12 }
13

14 public static void main ( String [] args ) {


15 String words1 [] = { " ab " , " c " };
16 String words2 [] = { " a " , " bc " };
17 System . out . println ( arrayStringsAreEqual ( words1 , words2 ) ) ;
18 }
19 }
Listing 20: Check if two string arrays are equal
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗M aximum69N umberT hismethodmaximizesanumber

9
1 class Solution {
2 public static int maximum69Number ( int num ) {
3 char arr [] = String . valueOf ( num ) . toCharArray () ;
4 int n = arr . length ;
5 for ( int i = 0; i < n ; i ++) {
6 if ( arr [ i ] == ’6 ’) {
7 arr [ i ] = ’9 ’;
8 break ;
9 }
10 }
11 return Integer . parseInt ( new String ( arr ) ) ;
12 }
13

14 public static void main ( String [] args ) {


15 System . out . println ( maximum69Number (9669) ) ;
16 }
17 }

Listing 21: Maximize number by changing one 6 to 9

1 Array Problems

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗IsP ossibletoSplitT hismethodchecksif anarraycanbespliti


sizedarrayswithdistinctelements.
1 import java . util . HashMap ;
2 import java . util . Map ;
3

4 class Solution {
5 public static boolean isPossibleToSplit ( int [] nums ) {
6 int n = nums . length ;
7 Map < Integer , Integer > mp1 = new HashMap < >() ;
8 for ( int i : nums ) {
9 int val = mp1 . getOrDefault (i , 0) ;
10 mp1 . put (i , val + 1) ;
11 if ( mp1 . get ( i ) > 2) {
12 return false ;
13 }
14 }
15 return true ;
16 }
17

18 public static void main ( String [] args ) {


19 int arr [] = {1 , 1 , 1 , 1};
20 System . out . println ( isPossibleToSplit ( arr ) ) ;
21 }
22 }

Listing 22: Check if array can be split into two distinct arrays

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗M aximumP roductSubarrayT hismethodf indsthemaxi


1 class Solution {
2 public static int maxProduct ( int [] nums ) {
3 int max = nums [0] , currMax = nums [0] , currMin = nums [0];
4 for ( int i = 1; i < nums . length ; i ++) {
5 int temp = currMax ;
6 currMax = Math . max ( nums [ i ] , Math . max ( currMax * nums [ i ] , currMin * nums [ i ]) ) ;
7 currMin = Math . min ( nums [ i ] , Math . min ( temp * nums [ i ] , currMin * nums [ i ]) ) ;
8 max = Math . max ( max , currMax ) ;

10
9 }
10 return max ;
11 }
12

13 public static void main ( String [] args ) {


14 int [] arr = {2 , 3 , -2 , 4};
15 System . out . println ( maxProduct ( arr ) ) ;
16 }
17 }

Listing 23: Find maximum product of a subarray

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗CheckSortedandRotatedArrayT hismethodchecksif an


1 class Solution {
2 public static boolean check ( int [] nums ) {
3 int n = nums . length ;
4 if ( n == 0) {
5 return false ;
6 }
7 if ( n == 1) {
8 return true ;
9 }
10 int count = 0;
11 for ( int i = 0; i < n ; i ++) {
12 if ( nums [ i ] > nums [( i + 1) % n ]) {
13 count ++;
14 }
15 if ( count > 1) {
16 return false ;
17 }
18 }
19 return true ;
20 }
21

22 public static void main ( String [] args ) {


23 int arr [] = {2 , 1 , 3 , 4};
24 System . out . println ( check ( arr ) ) ;
25 }
26 }

Listing 24: Check if array is sorted and rotated

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗RotateArrayT hismethodrotatesanarraytotherightbyk


1 class Solution {
2 public static void reverse ( int [] nums , int st , int end ) {
3 if ( st > end ) {
4 return ;
5 }
6 int temp = nums [ st ];
7 nums [ st ] = nums [ end ];
8 nums [ end ] = temp ;
9 reverse ( nums , st + 1 , end - 1) ;
10 }
11

12 public static void rotate ( int [] nums , int k ) {


13 int n = nums . length ;
14 k = k % n;
15 reverse ( nums , 0 , n - 1) ;
16 reverse ( nums , 0 , k - 1) ;
17 reverse ( nums , k , n - 1) ;
18 }
19

11
20 public static void main ( String [] args ) {
21 int [] arr = {1 , 2 , 3 , 4 , 5 , 6 , 7};
22 int k = 3;
23 rotate ( arr , k ) ;
24 for ( int i : arr ) {
25 System . out . println ( i ) ;
26 }
27 }
28 }

Listing 25: Rotate array to the right by k steps

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗M aximumConsecutiveOnesT hismethodf indsthemaxi


1 class Solution {
2 public static int f in dM axC on se cut iv eO nes ( int [] nums ) {
3 int count = 0;
4 int curr = 0;
5 int n = nums . length ;
6 for ( int i = 0; i < n ; i ++) {
7 if ( nums [ i ] == 1) {
8 curr ++;
9 count = Math . max ( count , curr ) ;
10 } else {
11 curr = 0;
12 }
13 }
14 return count ;
15 }
16

17 public static void main ( String [] args ) {


18 int arr [] = {1 , 0 , 1 , 1 , 0};
19 System . out . println ( f in dM axC on se cut iv eO nes ( arr ) ) ;
20 }
21 }

Listing 26: Find maximum consecutive ones

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗RearrangeArrayT hismethodrearrangesanarraytoalte


1 class Solution {
2 public static int [] rearrangeArray ( int [] nums ) {
3 int n = nums . length ;
4 int [] arr = new int [ n ];
5 int pos = 0 , neg = 1;
6 for ( int i = 0; i < n ; i ++) {
7 if ( nums [ i ] > 0) {
8 arr [ pos ] = nums [ i ];
9 pos += 2;
10 } else {
11 arr [ neg ] = nums [ i ];
12 neg += 2;
13 }
14 }
15 return arr ;
16 }
17 }

Listing 27: Rearrange array to alternate positive and negative numbers

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗LongestConsecutiveSequenceT hismethodf indstheleng


1 import java . util . HashSet ;
2 import java . util . Set ;
3

12
4 class Solution {
5 public static int longestConsecutive ( int [] nums ) {
6 int longest = 0;
7 Set < Integer > set = new HashSet < >() ;
8 for ( int i : nums ) {
9 set . add ( i ) ;
10 }
11 for ( int i : nums ) {
12 if (! set . contains ( i - 1) ) {
13 int cnt = 1;
14 int x = i ;
15 while ( set . contains ( x + 1) ) {
16 cnt ++;
17 x ++;
18 }
19 longest = Math . max ( cnt , longest ) ;
20 }
21 }
22 return longest ;
23 }
24 }

Listing 28: Find longest consecutive sequence

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗SetM atrixZeroesT hismethodsetsrowsandcolumnstoz


1 import java . util . Arrays ;
2

3 class Solution {
4 public static void setZeroes ( int [][] matrix ) {
5 int m = matrix . length ;
6 int n = matrix [0]. length ;
7 int rows [] = new int [ m ];
8 int cols [] = new int [ n ];
9 for ( int i = 0; i < m ; i ++) {
10 for ( int j = 0; j < n ; j ++) {
11 if ( matrix [ i ][ j ] == 0) {
12 rows [ i ] = 1;
13 cols [ j ] = 1;
14 }
15 }
16 }
17 for ( int i = 0; i < m ; i ++) {
18 for ( int j = 0; j < n ; j ++) {
19 if ( rows [ i ] == 1 || cols [ j ] == 1) {
20 matrix [ i ][ j ] = 0;
21 }
22 }
23 }
24 }
25

26 public static void main ( String [] args ) {


27 int mat [][] = {{1 , 1 , 1} , {1 , 0 , 1} , {1 , 1 , 1}};
28 setZeroes ( mat ) ;
29 }
30 }

Listing 29: Set matrix rows and columns to zero

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗SpiralM atrixT hismethodtraversesamatrixinaspiralo


1 import java . util . ArrayList ;
2 import java . util . List ;
3

13
4 class Solution {
5 public static List < Integer > spiralOrder ( int [][] matrix ) {
6 List < Integer > list = new ArrayList < >() ;
7 int m = matrix . length , n = matrix [0]. length ;
8 int left = 0 , top = 0 , right = n - 1 , bottom = m - 1;
9 while ( left <= right && top <= bottom ) {
10 for ( int i = left ; i <= right ; i ++) {
11 list . add ( matrix [ top ][ i ]) ;
12 }
13 top ++;
14 for ( int i = top ; i <= bottom ; i ++) {
15 list . add ( matrix [ i ][ right ]) ;
16 }
17 right - -;
18 if ( top <= bottom ) {
19 for ( int i = right ; i >= left ; i - -) {
20 list . add ( matrix [ bottom ][ i ]) ;
21 }
22 bottom - -;
23 }
24 if ( left <= right ) {
25 for ( int i = bottom ; i >= top ; i - -) {
26 list . add ( matrix [ i ][ left ]) ;
27 }
28 left ++;
29 }
30 }
31 return list ;
32 }
33

34 public static void main ( String [] args ) {


35 int mat [][] = {{1 , 2 , 3} , {4 , 5 , 6} , {7 , 8 , 9}};
36 System . out . println ( spiralOrder ( mat ) ) ;
37 }
38 }

Listing 30: Traverse matrix in spiral order

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗SubarraySumEqualsKT hismethodcountssubarraysw


1 class Solution {
2 public static int subarraySum ( int [] nums , int k ) {
3 int count = 0;
4 int sum = 0;
5 Map < Integer , Integer > map = new HashMap < >() ;
6 map . put (0 , 1) ;
7 for ( int i = 0; i < nums . length ; i ++) {
8 sum += nums [ i ];
9 if ( map . containsKey ( sum - k ) ) {
10 count += map . get ( sum - k ) ;
11 }
12 map . put ( sum , map . getOrDefault ( sum , 0) + 1) ;
13 }
14 return count ;
15 }
16

17 public static void main ( String [] args ) {


18 int [] arr = {1 , 1 , 1};
19 System . out . println ( subarraySum ( arr , 2) ) ;
20 }
21 }

Listing 31: Count subarrays with sum k

14
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗StringM atching(KM P )T hismethodf indsthef irstoccu
1 class Solution {
2 public static int strStr ( String haystack , String needle ) {
3 int n = haystack . length () , m = needle . length () ;
4 if ( m == 0) return 0;
5 for ( int i = 0; i <= n - m ; i ++) {
6 if ( haystack . substring (i , i + m ) . equals ( needle ) ) {
7 return i ;
8 }
9 }
10 return -1;
11 }
12

13 public static void main ( String [] args ) {


14 String h = " asadbutsad " ;
15 String n = " sad " ;
16 System . out . println ( strStr (h , n ) ) ;
17 }
18 }

Listing 32: Find first occurrence of needle in haystack

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗BinarySearchT hismethodperf ormsabinarysearchona


1 class Solution {
2 public static int search ( int [] nums , int target ) {
3 int n = nums . length ;
4 int low = 0 , high = n - 1;
5 while ( low <= high ) {
6 int mid = low + ( high - low ) / 2;
7 if ( nums [ mid ] == target ) {
8 return mid ;
9 } else if ( nums [ mid ] < target ) {
10 low = mid + 1;
11 } else {
12 high = mid - 1;
13 }
14 }
15 return -1;
16 }
17 }

Listing 33: Perform binary search on sorted array

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗SortedSquaresT hismethodreturnsanarrayof squareso


1 class Solution {
2 public static int [] sortedSquares ( int [] nums ) {
3 int res [] = new int [ nums . length ];
4 int n = nums . length ;
5 int low = 0 , high = n - 1;
6 for ( int i = n - 1; i >= 0; i - -) {
7 if ( Math . abs ( nums [ low ]) < Math . abs ( nums [ high ]) ) {
8 res [ i ] = nums [ high ] * nums [ high ];
9 high = high - 1;
10 } else {
11 res [ i ] = nums [ low ] * nums [ low ];
12 low = low + 1;
13 }
14 }
15 return res ;
16 }
17

15
18 public static void main ( String [] args ) {
19 int arr [] = { -4 , -1 , 0 , 3 , 10};
20 for ( int i : sortedSquares ( arr ) ) {
21 System . out . print ( i + " " ) ;
22 }
23 }
24 }

Listing 34: Return sorted array of squares

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗Intersectionof T woArraysT hismethodf indstheinterse


1 import java . util . HashSet ;
2 import java . util . Set ;
3 import java . util . ArrayList ;
4 import java . util . List ;
5

6 class Solution {
7 public static int [] intersection ( int [] nums1 , int [] nums2 ) {
8 Set < Integer > set = new HashSet < >() ;
9 List < Integer > result = new ArrayList < >() ;
10 for ( int num : nums1 ) {
11 set . add ( num ) ;
12 }
13 for ( int num : nums2 ) {
14 if ( set . contains ( num ) ) {
15 result . add ( num ) ;
16 set . remove ( num ) ;
17 }
18 }
19 int [] res = new int [ result . size () ];
20 for ( int i = 0; i < result . size () ; i ++) {
21 res [ i ] = result . get ( i ) ;
22 }
23 return res ;
24 }
25 }

Listing 35: Find intersection of two arrays

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗GuessN umberT hismethodf indsanumberusingaguessA


1 class GuessGame {
2 static int guess ( int n ) {
3 return n ; // Placeholder for actual guess API
4 }
5 }
6

7 class Solution extends GuessGame {


8 public static int guessNumber ( int n ) {
9 int left = 1 , high = n ;
10 while ( left <= high ) {
11 int mid = left + ( high - left ) / 2;
12 int res = guess ( mid ) ;
13 if ( res == 0) {
14 return mid ;
15 } else if ( res == 1) {
16 left = mid + 1;
17 } else {
18 high = mid - 1;
19 }
20 }
21 return -1;
22 }

16
23 }

Listing 36: Guess a number using binary search

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗N umberof GoodP airsT hismethodcountsthenumberof


1 class Solution {
2 public static int numIdenticalPairs ( int [] nums ) {
3 int count = 0 , n = nums . length ;
4 Map < Integer , Integer > map = new HashMap < >() ;
5 for ( int num : nums ) {
6 if ( map . containsKey ( num ) ) {
7 count += map . get ( num ) ;
8 map . put ( num , map . get ( num ) + 1) ;
9 } else {
10 map . put ( num , 1) ;
11 }
12 }
13 return count ;
14 }
15

16 public static void main ( String [] args ) {


17 int arr [] = {1 , 2 , 3 , 1 , 1 , 3};
18 System . out . println ( numIdenticalPairs ( arr ) ) ;
19 }
20 }

Listing 37: Count identical pairs in an array

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗T hirdM aximumN umberT hismethodf indsthethirdma


1 import java . util . PriorityQueue ;
2 import java . util . HashSet ;
3

4 class Solution {
5 public static int thirdMax ( int [] nums ) {
6 PriorityQueue < Integer > pq = new PriorityQueue < >() ;
7 HashSet < Integer > set = new HashSet < >() ;
8 for ( int num : nums ) {
9 if ( set . add ( num ) ) {
10 pq . offer ( num ) ;
11 if ( pq . size () > 3) {
12 pq . poll () ;
13 }
14 }
15 }
16 if ( pq . size () < 3) {
17 while ( pq . size () > 1) {
18 pq . poll () ;
19 }
20 return pq . peek () ;
21 }
22 return pq . peek () ;
23 }
24

25 public static void main ( String [] args ) {


26 int [] arr = {3 , 2 , 1};
27 System . out . println ( thirdMax ( arr ) ) ;
28 }
29 }

Listing 38: Find third maximum number in array

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F indDisappearedN umbersT hismethodf indsnumbersm

17
1 import java . util . ArrayList ;
2 import java . util . HashMap ;
3 import java . util . List ;
4 import java . util . Map ;
5

6 class Solution {
7 public static List < Integer > f in dD isa pp ea red Nu mb ers ( int [] nums ) {
8 List < Integer > list = new ArrayList < >() ;
9 Map < Integer , Integer > hmap = new HashMap < >() ;
10 int l = 1 , h = nums . length ;
11 for ( int i : nums ) {
12 hmap . put (i , hmap . getOrDefault (i , 0) + 1) ;
13 }
14 for ( int i = l ; i <= h ; i ++) {
15 if ( hmap . getOrDefault (i , 0) == 0) {
16 list . add ( i ) ;
17 }
18 }
19 return list ;
20 }
21

22 public static void main ( String [] args ) {


23 int arr [] = {4 , 3 , 2 , 7 , 8 , 2 , 3 , 1};
24 System . out . println ( f in dD isa pp ea red Nu mb ers ( arr ) ) ;
25 }
26 }

Listing 39: Find missing numbers in array

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗CountN egativesT hismethodcountsnegativenumbersin


1 class Solution {
2 public static int count ( int [] arr ) {
3 int n = arr . length , cont = 0;
4 for ( int i : arr ) {
5 if ( i < 0) {
6 cont ++;
7 }
8 }
9 return cont ;
10 }
11

12 public static int countNegatives ( int [][] grid ) {


13 int count = 0;
14 int r = grid . length ;
15 for ( int i = 0; i < r ; i ++) {
16 count = count + count ( grid [ i ]) ;
17 }
18 return count ;
19 }
20 }

Listing 40: Count negative numbers in sorted matrix

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗M aximumCountT hismethodf indsthemaximumcount


1 class Solution {
2 public static int maximumCount ( int [] nums ) {
3 int neg = 0 , pos = 0;
4 for ( int i : nums ) {
5 if ( i > 0) {
6 pos ++;
7 } else if ( i < 0) {

18
8 neg ++;
9 }
10 }
11 return Math . max ( neg , pos ) ;
12 }
13 }

Listing 41: Find maximum count of positive or negative numbers

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F indCommonElementT hismethodf indsthesmallestco


1 import java . util . HashSet ;
2 import java . util . Set ;
3

4 class Solution {
5 public int getCommon ( int [] nums1 , int [] nums2 ) {
6 Set < Integer > set = new HashSet < >() ;
7 for ( int i : nums1 ) {
8 set . add ( i ) ;
9 }
10 for ( int i : nums2 ) {
11 if ( set . contains ( i ) ) {
12 return i ;
13 }
14 }
15 return -1;
16 }
17 }

Listing 42: Find smallest common element in two arrays

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗HasAlternatingBitsT hismethodchecksif thebinaryrep


1 class Solution {
2 public static boolean hasAlternatingBits ( int n ) {
3 String str = Integer . toBinaryString ( n ) ;
4 char prev = str . charAt (0) ;
5 for ( int i = 1; i < str . length () ; i ++) {
6 if ( prev == str . charAt ( i ) ) {
7 return false ;
8 }
9 prev = str . charAt ( i ) ;
10 }
11 return true ;
12 }
13 }

Listing 43: Check if binary representation has alternating bits

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ArrayConcatenationT hismethodconcatenatesanarray


1 class Solution {
2 public int [] getConcatenation ( int [] nums ) {
3 int arr [] = new int [ nums . length * 2];
4 int j = 0 , n = nums . length ;
5 for ( int i = 0; i < nums . length ; i ++) {
6 arr [ j ] = nums [ i ];
7 arr [ j + n ] = nums [ i ];
8 j ++;
9 }
10 return arr ;
11 }
12 }

Listing 44: Concatenate array with itself

19
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗BaseballGameT hismethodcalculatesthetotalscoreof ab
1 import java . util . ArrayList ;
2 import java . util . List ;
3

4 class Solution {
5 public static int calPoints ( String [] operations ) {
6 int count = 0;
7 List < Integer > list = new ArrayList < >() ;
8 for ( String op : operations ) {
9 if ( op . equals ( " C " ) ) {
10 if (! list . isEmpty () ) {
11 list . remove ( list . size () - 1) ;
12 }
13 } else if ( op . equals ( " D " ) ) {
14 if (! list . isEmpty () ) {
15 list . add ( list . get ( list . size () - 1) * 2) ;
16 }
17 } else if ( op . equals ( " + " ) ) {
18 if ( list . size () >= 2) {
19 int n = list . size () ;
20 int val1 = list . get ( n - 1) ;
21 int val2 = list . get ( n - 2) ;
22 list . add ( val2 + val1 ) ;
23 }
24 } else {
25 list . add ( Integer . parseInt ( op ) ) ;
26 }
27 }
28 count = list . stream () . reduce (0 , Integer :: sum ) ;
29 return count ;
30 }
31

32 public static void main ( String [] args ) {


33 String op [] = { " 5 " , " 2 " , " C " , " D " , " + " };
34 System . out . println ( calPoints ( op ) ) ;
35 }
36 }
Listing 45: Calculate baseball game score
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗JewelsandStonesT hismethodcountshowmanystonesar
1 import java . util . HashMap ;
2 import java . util . Map ;
3

4 class Solution {
5 public static int numJewelsInStones ( String jewels , String stones ) {
6 int count = 0;
7 Map < Character , Integer > hmap = new HashMap < >() ;
8 for ( char c : stones . toCharArray () ) {
9 hmap . put (c , hmap . getOrDefault (c , 0) + 1) ;
10 }
11 for ( char c : jewels . toCharArray () ) {
12 int val = hmap . getOrDefault (c , 0) ;
13 count = count + val ;
14 }
15 return count ;
16 }
17

18 public static void main ( String [] args ) {


19 System . out . println ( numJewelsInStones ( " aA " , " aAAbbbb " ) ) ;
20 }
21 }

20
Listing 46: Count jewels in stones

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F izzBuzzT hismethodgeneratesaF izzBuzzsequenceup


1 import java . util . ArrayList ;
2 import java . util . List ;
3

4 class Solution {
5 public static List < String > fizzBuzz ( int n ) {
6 List < String > list = new ArrayList < >() ;
7 for ( int i = 1; i <= n ; i ++) {
8 if ( i % 3 == 0 && i % 5 == 0) {
9 list . add ( " FizzBuzz " ) ;
10 } else if ( i % 3 == 0) {
11 list . add ( " Fizz " ) ;
12 } else if ( i % 5 == 0) {
13 list . add ( " Buzz " ) ;
14 } else {
15 list . add ( " " + i ) ;
16 }
17 }
18 return list ;
19 }
20

21 public static void main ( String [] args ) {


22 System . out . println ( fizzBuzz (15) ) ;
23 }
24 }

Listing 47: Generate FizzBuzz sequence

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗V alidP arenthesesT hismethodchecksif astringof paren


1 import java . util . Stack ;
2

3 class Solution {
4 public static boolean isValid ( String s ) {
5 Stack < Character > stack = new Stack < >() ;
6 for ( char c : s . toCharArray () ) {
7 if ( c == ’( ’ || c == ’{ ’ || c == ’[ ’) {
8 stack . push ( c ) ;
9 } else {
10 if ( stack . isEmpty () ) return false ;
11 char top = stack . pop () ;
12 if (( c == ’) ’ && top != ’( ’) ||
13 ( c == ’} ’ && top != ’{ ’) ||
14 ( c == ’] ’ && top != ’[ ’) ) {
15 return false ;
16 }
17 }
18 }
19 return stack . isEmpty () ;
20 }
21 }

Listing 48: Check valid parentheses

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗HammingW eightT hismethodcountsthenumberof 1sin


1 class Solution {
2 public static int hammingWeight ( int n ) {
3 int count = 0;
4 while ( n != 0) {

21
5 if (( n & 1) == 1) {
6 count ++;
7 }
8 n = n >>> 1; // Use unsigned right shift
9 }
10 return count ;
11 }
12

13 public static void main ( String [] args ) {


14 System . out . println ( hammingWeight (2147483645) ) ;
15 }
16 }

Listing 49: Count 1s in binary representation

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ReverseBitsT hismethodreversesthebitsof a32−


bitinteger.
1 class Solution {
2 public static int reverseBits ( int n ) {
3 String bin1 = Integer . toBinaryString ( n ) ;
4 int reqLen = 32 - bin1 . length () ;
5 String bin = " " ;
6 while ( reqLen > 0) {
7 bin = bin + " 0 " ;
8 reqLen - -;
9 }
10 bin1 = bin + bin1 ;
11 StringBuilder sb = new StringBuilder ( bin1 ) ;
12 sb . reverse () ;
13 return ( int ) Long . parseLong ( sb . toString () , 2) ;
14 }
15

16 public static void main ( String [] args ) {


17 System . out . println ( reverseBits (43261596) ) ;
18 }
19 }

Listing 50: Reverse bits of a 32-bit integer

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ContainsN earbyDuplicateT hismethodchecksif therea


1 import java . util . HashMap ;
2 import java . util . Map ;
3

4 class Solution {
5 public static boolean co nt a in s Ne ar b yD u pl ic a te ( int [] nums , int k ) {
6 Map < Integer , Integer > hmap = new HashMap < >() ;
7 for ( int i = 0; i < nums . length ; i ++) {
8 int num = nums [ i ];
9 if ( hmap . containsKey ( num ) && i - hmap . get ( num ) <= k ) {
10 return true ;
11 }
12 hmap . put ( num , i ) ;
13 }
14 return false ;
15 }
16 }

Listing 51: Check for duplicates within k distance

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗BestT imetoBuyandSellStockT hismethodf indsthemax


1 import java . util . Arrays ;
2

22
3 class Solution {
4 public static int maxProfit ( int [] prices ) {
5 int min = Integer . MAX_VALUE ;
6 int maxProfit = 0;
7 for ( int price : prices ) {
8 min = Math . min ( min , price ) ;
9 maxProfit = Math . max ( maxProfit , price - min ) ;
10 }
11 return maxProfit ;
12 }
13

14 public static void main ( String [] args ) {


15 int arr [] = {7 , 5 , 4 , 3 , 2 , 1};
16 System . out . println ( maxProfit ( arr ) ) ;
17 }
18 }

Listing 52: Find maximum stock profit

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F indM issingandRepeatedV aluesT hismethodf indsthe


1 import java . util . HashMap ;
2 import java . util . Map ;
3

4 class Solution {
5 public static int [] f i n d M i s s i n g A n d R e p e a t e d V a l u e s ( int [][] grid ) {
6 int n = grid . length ;
7 int arr [] = new int [2];
8 Map < Integer , Integer > hmap = new HashMap < >() ;
9 for ( int i = 0; i < n ; i ++) {
10 for ( int j = 0; j < n ; j ++) {
11 int ele = grid [ i ][ j ];
12 hmap . put ( ele , hmap . getOrDefault ( ele , 0) + 1) ;
13 }
14 }
15 for ( int i = 1; i <= n * n ; i ++) {
16 if ( hmap . getOrDefault (i , 0) == 2) {
17 arr [0] = i ;
18 } else if ( hmap . getOrDefault (i , 0) == 0) {
19 arr [1] = i ;
20 }
21 }
22 return arr ;
23 }
24

25 public static void main ( String [] args ) {


26 int [][] grids = {{1 , 3} , {2 , 2}};
27 for ( int i : f i n d M i s s i n g A n d R e p e a t e d V a l u e s ( grids ) ) {
28 System . out . print ( i + " " ) ;
29 }
30 }
31 }

Listing 53: Find repeated and missing numbers in grid

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗M ajorityElementT hismethodf indselementsappearing


class Solution public static List¡Integer¿ majorityElement(int[] nums) List¡Integer¿ list = new ArrayList¡¿(); if
(nums.length == 0) return list; int count1 = 0, count2 = 0, candidate1 = 0, candidate2 = 1; for (int num : nums)
if (num == candidate1) count1++; else if (num == candidate2) count2++; else if (count1 == 0) candidate1 =
num; count1++; else if (count2 == 0) candidate2 = num; count2++; else count1–; count2–; count1 = count2
= 0; for (int num : nums) if (num == candidate1) count1++; else if (num == candidate2) count2++; if (count1
¿ nums.length / 3) list.add(candidate1); if (count2 ¿ nums.length / 3) list.add(candidate2); return list;

23
1 Binary Tree Problems

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗P athSumT hismethodchecksif thereexistsaroot−


to − leaf pathsummingtotargetSum.
1 class TreeNode {
2 int val ;
3 TreeNode left ;
4 TreeNode right ;
5 TreeNode () {}
6 TreeNode ( int val ) { this . val = val ; }
7 TreeNode ( int val , TreeNode left , TreeNode right ) {
8 this . val = val ;
9 this . left = left ;
10 this . right = right ;
11 }
12 }
13

14 class Solution {
15 public boolean hasPathSum ( TreeNode root , int targetSum ) {
16 if ( root == null ) {
17 return false ;
18 }
19 if ( root . left == null && root . right == null ) {
20 return targetSum == root . val ;
21 }
22 return hasPathSum ( root . left , targetSum - root . val ) ||
23 hasPathSum ( root . right , targetSum - root . val ) ;
24 }
25 }

Listing 54: Check for a path sum in a binary tree

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗V alidateBinarySearchT reeT hismethodvalidatesif abi


1 import java . util . ArrayList ;
2 import java . util . List ;
3

4 class Solution {
5 public static void inorder ( TreeNode root , List < Integer > list ) {
6 if ( root == null ) {
7 return ;
8 }
9 inorder ( root . left , list ) ;
10 list . add ( root . val ) ;
11 inorder ( root . right , list ) ;
12 }
13

14 public boolean isValidBST ( TreeNode root ) {


15 List < Integer > list = new ArrayList < >() ;
16 inorder ( root , list ) ;
17 for ( int i = 0; i < list . size () - 1; i ++) {
18 if ( list . get ( i ) >= list . get ( i + 1) ) {
19 return false ;
20 }
21 }
22 return true ;
23 }
24 }

Listing 55: Validate a Binary Search Tree

24
startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗ZigzagLevelOrderT raversalT hismethodperf ormsazi
ordertraversalof abinarytree.
1 import java . util . ArrayList ;
2 import java . util . Collections ;
3 import java . util . LinkedList ;
4 import java . util . List ;
5 import java . util . Queue ;
6

7 class Solution {
8 public List < List < Integer > > zigzagLevelOrder ( TreeNode root ) {
9 List < List < Integer > > list = new ArrayList < >() ;
10 if ( root == null ) {
11 return list ;
12 }
13 Queue < TreeNode > queue = new LinkedList < >() ;
14 queue . add ( root ) ;
15 int level = 0;
16 while (! queue . isEmpty () ) {
17 int size = queue . size () ;
18 List < Integer > arr = new ArrayList < >() ;
19 for ( int i = 0; i < size ; i ++) {
20 TreeNode treeNode = queue . poll () ;
21 arr . add ( treeNode . val ) ;
22 if ( treeNode . left != null ) {
23 queue . add ( treeNode . left ) ;
24 }
25 if ( treeNode . right != null ) {
26 queue . add ( treeNode . right ) ;
27 }
28 }
29 if ( level % 2 != 0) {
30 Collections . reverse ( arr ) ;
31 }
32 level ++;
33 list . add ( arr ) ;
34 }
35 return list ;
36 }
37 }

Listing 56: Zigzag level-order traversal of a binary tree

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗BalancedBinaryT reeT hismethodchecksif abinarytree


balanced.
1 class Solution {
2 public static int check ( TreeNode root ) {
3 if ( root == null ) {
4 return 0;
5 }
6 int left = check ( root . left ) ;
7 int right = check ( root . right ) ;
8 return 1 + Math . max ( left , right ) ;
9 }
10

11 public boolean isBalanced ( TreeNode root ) {


12 if ( root == null ) {
13 return true ;
14 }
15 int lh = check ( root . left ) ;
16 int rh = check ( root . right ) ;
17 if ( Math . abs ( lh - rh ) > 1) {

25
18 return false ;
19 }
20 boolean left = isBalanced ( root . left ) ;
21 boolean right = isBalanced ( root . right ) ;
22 return left && right ;
23 }
24 }

Listing 57: Check if a binary tree is height-balanced

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗Diameterof BinaryT reeT hismethodcalculatesthediam


1 class Solution {
2 int max = 0;
3

4 public int height ( TreeNode root ) {


5 if ( root == null ) {
6 return 0;
7 }
8 int left = height ( root . left ) ;
9 int right = height ( root . right ) ;
10 max = Math . max ( max , left + right ) ;
11 return 1 + Math . max ( left , right ) ;
12 }
13

14 public int diameterOfBinaryTree ( TreeNode root ) {


15 height ( root ) ;
16 return max ;
17 }
18 }

Listing 58: Calculate diameter of a binary tree

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗M inimumDepthof BinaryT reeT hismethodf indsthem


1 class Solution {
2 public int minDepth ( TreeNode root ) {
3 if ( root == null ) {
4 return 0;
5 }
6 int left = minDepth ( root . left ) ;
7 int right = minDepth ( root . right ) ;
8 if ( root . left == null || root . right == null ) {
9 return 1 + Math . max ( left , right ) ;
10 }
11 return 1 + Math . min ( left , right ) ;
12 }
13 }

Listing 59: Find minimum depth of a binary tree

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗SearchinBST T hismethodsearchesf oravalueinaBinar


1 import java . util . LinkedList ;
2 import java . util . Queue ;
3

4 class Solution {
5 public static TreeNode searchBST ( TreeNode root , int val ) {
6 if ( root == null || root . val == val ) {
7 return root ;
8 }
9 if ( val < root . val ) {
10 return searchBST ( root . left , val ) ;
11 }
12 return searchBST ( root . right , val ) ;

26
13 }
14 }

Listing 60: Search for a value in a BST

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗SortedArraytoBST T hismethodconvertsasortedarrayt


1 class Solution {
2 public TreeNode sortedArrayToBST ( int [] nums ) {
3 if ( nums == null || nums . length == 0) {
4 return null ;
5 }
6 return constructBST ( nums , 0 , nums . length - 1) ;
7 }
8

9 private TreeNode constructBST ( int [] nums , int left , int right ) {


10 if ( left > right ) {
11 return null ;
12 }
13 int mid = left + ( right - left ) / 2;
14 TreeNode node = new TreeNode ( nums [ mid ]) ;
15 node . left = constructBST ( nums , left , mid - 1) ;
16 node . right = constructBST ( nums , mid + 1 , right ) ;
17 return node ;
18 }
19 }

Listing 61: Convert sorted array to balanced BST

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗Sumof Lef tLeavesT hismethodcalculatesthesumof alll


1 class Solution {
2 public static int sumOfLeftLeaves ( TreeNode root ) {
3 if ( root == null ) {
4 return 0;
5 }
6 int sum = 0;
7 if ( root . left != null && root . left . left == null && root . left . right == null ) {
8 sum += root . left . val ;
9 }
10 sum += sumOfLeftLeaves ( root . left ) ;
11 sum += sumOfLeftLeaves ( root . right ) ;
12 return sum ;
13 }
14 }

Listing 62: Sum of left leaves in a binary tree

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗AllT raversalsinOneT hismethodperf ormspreorder, in


1 import java . util . ArrayList ;
2 import java . util . List ;
3 import java . util . Stack ;
4

5 class Node {
6 int data ;
7 Node left , right ;
8 public Node ( int data ) {
9 this . data = data ;
10 this . left = this . right = null ;
11 }
12 }
13

14 class Pair {
15 Node node ;

27
16 int val ;
17 public Pair ( Node node , int val ) {
18 this . node = node ;
19 this . val = val ;
20 }
21 }
22

23 class Tree {
24 public static void genDfs ( Node root ) {
25 List < Integer > pre = new ArrayList < >() ;
26 List < Integer > post = new ArrayList < >() ;
27 List < Integer > ino = new ArrayList < >() ;
28 Stack < Pair > stack = new Stack < >() ;
29 stack . push ( new Pair ( root , 1) ) ;
30 while (! stack . isEmpty () ) {
31 Pair pair = stack . peek () ;
32 if ( pair . val == 1) {
33 pre . add ( pair . node . data ) ;
34 pair . val ++;
35 if ( pair . node . left != null ) {
36 stack . add ( new Pair ( pair . node . left , 1) ) ;
37 }
38 } else if ( pair . val == 2) {
39 ino . add ( pair . node . data ) ;
40 pair . val ++;
41 if ( pair . node . right != null ) {
42 stack . add ( new Pair ( pair . node . right , 1) ) ;
43 }
44 } else {
45 post . add ( pair . node . data ) ;
46 stack . pop () ;
47 }
48 }
49 System . out . println ( " PREORDER IS " + pre ) ;
50 System . out . println ( " INORDER IS " + ino ) ;
51 System . out . println ( " POSTORDER IS " + post ) ;
52 }
53

54 public static void main ( String [] args ) {


55 Node root = new Node (1) ;
56 root . left = new Node (2) ;
57 root . right = new Node (5) ;
58 root . left . left = new Node (3) ;
59 root . left . right = new Node (4) ;
60 root . right . left = new Node (6) ;
61 root . right . right = new Node (7) ;
62 genDfs ( root ) ;
63 }
64 }

Listing 63: Perform all tree traversals in one pass

1 Linked List Problems

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗RemoveDuplicatesf romSortedListT hismethodremovesdu


1 import java . util . Set ;
2 import java . util . TreeSet ;
3

4 class ListNode {

28
5 int val ;
6 ListNode next ;
7 ListNode () {}
8 ListNode ( int val ) { this . val = val ; }
9 ListNode ( int val , ListNode next ) { this . val = val ; this . next = next ; }
10 }
11

12 class Solution1 {
13 public static ListNode deleteDuplicates ( ListNode head ) {
14 if ( head == null ) {
15 return null ;
16 }
17 ListNode newNode = new ListNode ( -1) ;
18 Set < Integer > set = new TreeSet < >() ;
19 ListNode curr = head ;
20 while ( curr != null ) {
21 set . add ( curr . val ) ;
22 curr = curr . next ;
23 }
24 ListNode tail = newNode ;
25 for ( int i : set ) {
26 ListNode listNode = new ListNode ( i ) ;
27 tail . next = listNode ;
28 tail = tail . next ;
29 }
30 return newNode . next ;
31 }
32

33 public static void main ( String [] args ) {


34 ListNode list = new ListNode (1) ;
35 list . next = new ListNode (1) ;
36 list . next . next = new ListNode (2) ;
37 ListNode res = deleteDuplicates ( list ) ;
38 while ( res != null ) {
39 System . out . println ( res . val ) ;
40 res = res . next ;
41 }
42 }
43 }

Listing 64: Remove duplicates from sorted linked list

1 Matrix Problems

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗F lipandInvertImageT hismethodf lipsabinarymatrixhoriz


1 class Solution {
2 public static int [] reverse ( int [] arr ) {
3 int n = arr . length ;
4 for ( int i = 0; i < n / 2; i ++) {
5 int temp = arr [ i ];
6 arr [ i ] = arr [ n - i - 1];
7 arr [ n - i - 1] = temp ;
8 }
9 return arr ;
10 }
11

12 public static int [] invert ( int [] arr ) {


13 int n = arr . length ;
14 for ( int i = 0; i < n ; i ++) {

29
15 arr [ i ] = arr [ i ] == 0 ? 1 : 0;
16 }
17 return arr ;
18 }
19

20 public static int [][] flipAndInvertImage ( int [][] image ) {


21 int r = image . length , c = image [0]. length ;
22 int [][] matrix = new int [ r ][ c ];
23 for ( int i = 0; i < r ; i ++) {
24 matrix [ i ] = reverse ( image [ i ]) ;
25 }
26 for ( int i = 0; i < r ; i ++) {
27 matrix [ i ] = invert ( matrix [ i ]) ;
28 }
29 return matrix ;
30 }
31 }

Listing 65: Flip and invert a binary matrix

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗LuckyN umbersT hismethodf indsluckynumbers(minim


1 import java . util . ArrayList ;
2 import java . util . List ;
3

4 class Solution {
5 public static List < Integer > luckyNumbers ( int [][] matrix ) {
6 List < Integer > list = new ArrayList < >() ;
7 if ( matrix == null ) {
8 return list ;
9 }
10 int r = matrix . length , c = matrix [0]. length ;
11 for ( int i = 0; i < r ; i ++) {
12 int min = Integer . MAX_VALUE , minCol = 0;
13 for ( int j = 0; j < c ; j ++) {
14 if ( matrix [ i ][ j ] < min ) {
15 min = matrix [ i ][ j ];
16 minCol = j ;
17 }
18 }
19 boolean isMax = true ;
20 for ( int k = 0; k < r ; k ++) {
21 if ( matrix [ k ][ minCol ] > min ) {
22 isMax = false ;
23 break ;
24 }
25 }
26 if ( isMax ) {
27 list . add ( min ) ;
28 }
29 }
30 return list ;
31 }
32

33 public static void main ( String [] args ) {


34 int [][] matrix = {{1 , 10 , 4 , 2} , {9 , 3 , 8 , 7} , {15 , 16 , 17 , 12}};
35 System . out . println ( luckyNumbers ( matrix ) ) ;
36 }
37 }

Listing 66: Find lucky numbers in a matrix

30
1 Miscellaneous Problems

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗M aximumW ealthT hismethodf indsthemaximumwealtha


1 class Solution {
2 public static int maximumWealth ( int [][] accounts ) {
3 int max = Integer . MIN_VALUE ;
4 int r = accounts . length ;
5 for ( int i = 0; i < r ; i ++) {
6 int sum = 0;
7 for ( int j = 0; j < accounts [ i ]. length ; j ++) {
8 sum += accounts [ i ][ j ];
9 }
10 max = Math . max ( max , sum ) ;
11 }
12 return max ;
13 }
14 }

Listing 67: Find maximum wealth among accounts

startsectionsubsection2@−3explus − 1exminus − .2ex1.5explus.2ex∗DoesAliceW inT hismethoddeterminesif Alicewinsaga


T heprovidedcodeisincomplete; thisisaplaceholdernotingitsstatus.)
1 class Solution {
2 public static int vow ( char [] ch ) {
3 int count = 0;
4 for ( char c : ch ) {
5 if ( c == ’a ’ || c == ’e ’ || c == ’i ’ || c == ’o ’ || c == ’u ’) {
6 count ++;
7 }
8 }
9 return count ;
10 }
11

12 public static String remStr ( String s ) {


13 String res = " " ;
14 // Incomplete logic for removing vowels
15 return res ;
16 }
17

18 public static boolean doesAliceWin ( String s ) {


19 // Incomplete : Logic to determine if Alice wins
20 return false ;
21 }
22 }

Listing 68: Incomplete: Determine if Alice wins by removing vowels

31

You might also like