From 1dba4f203d6d5fd6fe49bc0e743574048543d131 Mon Sep 17 00:00:00 2001 From: Arghya Das <95538110+alfaArghya@users.noreply.github.com> Date: Mon, 26 Jun 2023 11:47:31 +0530 Subject: [PATCH 1/4] Add files via upload --- 3_Strings/String09_Add2String.java | 73 ++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 3_Strings/String09_Add2String.java diff --git a/3_Strings/String09_Add2String.java b/3_Strings/String09_Add2String.java new file mode 100644 index 0000000..eb0fda6 --- /dev/null +++ b/3_Strings/String09_Add2String.java @@ -0,0 +1,73 @@ +/* +Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. + +You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. + + + +Example 1: + +Input: num1 = "11", num2 = "123" +Output: "134" + +Example 2: + +Input: num1 = "456", num2 = "77" +Output: "533" + +Example 3: + +Input: num1 = "0", num2 = "0" +Output: "0" + + + +Constraints: + + 1 <= num1.length, num2.length <= 104 + num1 and num2 consist of only digits. + num1 and num2 don't have any leading zeros except for the zero itself. + + +*/ + + +public class String09_Add2String { + + public static String addString(String num1, String num2) { //TC --> O(n) || SC --> O(1) + StringBuilder sb = new StringBuilder(""); + int n1 = num1.length()-1, n2 = num2.length()-1; + int sum, carry = 0; + + while(n1 >= 0 || n2 >= 0) { + sum = carry; + + if(n1 >= 0) { + sum += num1.charAt(n1) - '0'; + n1--; + } + if(n2 >= 0) { + sum += num2.charAt(n2) - '0'; + n2--; + } + + sb.append(sum%10); + carry = sum/10; + } + + if(carry != 0) { + sb.append(carry); + } + + return sb.reverse().toString(); + } + + + + public static void main(String[] args) { + String num1 = "9333852702227987", num2 = "85731737104263"; + + System.out.println(">> "+addString(num1, num2)); + + } +} \ No newline at end of file From b8cb76e15ebb5c79ffd4ca9b9a8f66b04e0c3e09 Mon Sep 17 00:00:00 2001 From: Arghya Das <95538110+alfaArghya@users.noreply.github.com> Date: Mon, 26 Jun 2023 11:52:02 +0530 Subject: [PATCH 2/4] Add files via upload --- .../String11_ValidPalindrome_AfterDelete.java | 61 ++++++++++++ 3_Strings/String12_RomanToInteger.java | 95 +++++++++++++++++++ .../String13_FirstOccurrenceInAString.java | 39 ++++++++ 3 files changed, 195 insertions(+) create mode 100644 3_Strings/String11_ValidPalindrome_AfterDelete.java create mode 100644 3_Strings/String12_RomanToInteger.java create mode 100644 3_Strings/String13_FirstOccurrenceInAString.java diff --git a/3_Strings/String11_ValidPalindrome_AfterDelete.java b/3_Strings/String11_ValidPalindrome_AfterDelete.java new file mode 100644 index 0000000..865cc59 --- /dev/null +++ b/3_Strings/String11_ValidPalindrome_AfterDelete.java @@ -0,0 +1,61 @@ +/* +Given a string s, return true if the s can be palindrome after deleting at most one character from it. + + + +Example 1: + +Input: s = "aba" +Output: true + +Example 2: + +Input: s = "abca" +Output: true +Explanation: You could delete the character 'c'. + +Example 3: + +Input: s = "abc" +Output: false + + + +Constraints: + + 1 <= s.length <= 105 + s consists of lowercase English letters. + + + */ +public class String11_ValidPalindrome_AfterDelete { + + public static boolean isPalindrome(String str) { //TC -> O(n^2) + int startIndex = 0, endIndex = str.length()-1; + while(startIndex < endIndex) { + if(str.charAt(startIndex) != str.charAt(endIndex)) { + return check(str, startIndex, endIndex-1) || check(str, startIndex+1, endIndex); + } + + startIndex++; + endIndex--; + } + + return true; //--> when loop ends completely + } + + public static boolean check(String str, int i, int j) { + while(i < j) { + if(str.charAt(i) != str.charAt(j)) { + return false; + } + i++; + j--; + } + return true; + } + + public static void main(String[] args) { + System.out.println(isPalindrome("abeea")); + } +} diff --git a/3_Strings/String12_RomanToInteger.java b/3_Strings/String12_RomanToInteger.java new file mode 100644 index 0000000..d11c25c --- /dev/null +++ b/3_Strings/String12_RomanToInteger.java @@ -0,0 +1,95 @@ +/* +Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 + +For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: + + I can be placed before V (5) and X (10) to make 4 and 9. + X can be placed before L (50) and C (100) to make 40 and 90. + C can be placed before D (500) and M (1000) to make 400 and 900. + +Given a roman numeral, convert it to an integer. + + + +Example 1: + +Input: s = "III" +Output: 3 +Explanation: III = 3. + +Example 2: + +Input: s = "LVIII" +Output: 58 +Explanation: L = 50, V= 5, III = 3. + +Example 3: + +Input: s = "MCMXCIV" +Output: 1994 +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + +Constraints: + + 1 <= s.length <= 15 + s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). + It is guaranteed that s is a valid roman numeral in the range [1, 3999] + */ + +public class String12_RomanToInteger { + + public static int convert(char r) { + if(r == 'I') return 1; + if(r == 'V') return 5; + if(r == 'X') return 10; + if(r == 'L') return 50; + if(r == 'C') return 100; + if(r == 'D') return 500; + if(r == 'M') return 1000; + + return -1; + } + + public static int romanTOinteger(String str) { //TC -> O(n) + int ans = 0; + int r1, r2; + + for(int i = 0; i < str.length(); i++) { + r1 = convert(str.charAt(i)); //convert and store ith element + //getting value of symbol of i+1th element + if(i+1 < str.length()) { + r2 = convert(str.charAt(i+1)); + + if(r1 >= r2) { + ans += r1; //value of current element is greater than nest element + } else { + ans += r2-r1; //value of current element is less than nest element + i++; + } + } else { + ans += r1; //if there is no i+1 th element available + } + } + + return ans; + + } + + + public static void main(String[] args) { + String roman = "XXX"; + + System.out.println(">> "+romanTOinteger(roman)); + } +} diff --git a/3_Strings/String13_FirstOccurrenceInAString.java b/3_Strings/String13_FirstOccurrenceInAString.java new file mode 100644 index 0000000..c8ee2e3 --- /dev/null +++ b/3_Strings/String13_FirstOccurrenceInAString.java @@ -0,0 +1,39 @@ +/* +Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. + +Example 1: + +Input: haystack = "sadbutsad", needle = "sad" +Output: 0 +Explanation: "sad" occurs at index 0 and 6. +The first occurrence is at index 0, so we return 0. + +Example 2: + +Input: haystack = "leetcode", needle = "leeto" +Output: -1 +Explanation: "leeto" did not occur in "leetcode", so we return -1. + +Constraints: + + 1 <= haystack.length, needle.length <= 104 + haystack and needle consist of only lowercase English characters. + */ + +public class String13_FirstOccurrenceInAString { + + public static int strStr(String haystack, String needle) { //TC -> O(n) + + for(int i = 0; i < haystack.length()-needle.length()+1; i++) { + if(haystack.substring(i, i+needle.length()).equals(needle)) { + return i; + } + } + return -1; + } + + public static void main(String[] args) { + String haystack = "leetcode", needle = "e"; + System.out.println(">> "+ strStr(haystack, needle)); + } +} \ No newline at end of file From 077fd1fc0b1b74642650f88460a92e220cccb0ef Mon Sep 17 00:00:00 2001 From: Arghya Das <95538110+alfaArghya@users.noreply.github.com> Date: Mon, 26 Jun 2023 11:59:20 +0530 Subject: [PATCH 3/4] Add files via upload --- 3_Strings/String01_PalindromeBasic.java | 22 ++++++ 3_Strings/String02_ShortestPath.java | 38 +++++++++ 3_Strings/String03_UpperCase.java | 30 +++++++ 3_Strings/String04_StringCompression.java | 42 ++++++++++ 3_Strings/String05_CountLowerCaseVowels.java | 24 ++++++ 3_Strings/String06_Anagrams.java | 74 ++++++++++++++++++ 3_Strings/String07_ValidPalindrome.java | 61 +++++++++++++++ 3_Strings/String08_LongestCommonPrefix.java | 26 ++++++ 3_Strings/String10_LongestCommonPrefix.java | 58 ++++++++++++++ .../String13_FirstOccurrenceInAString.class | Bin 0 -> 1044 bytes 10 files changed, 375 insertions(+) create mode 100644 3_Strings/String01_PalindromeBasic.java create mode 100644 3_Strings/String02_ShortestPath.java create mode 100644 3_Strings/String03_UpperCase.java create mode 100644 3_Strings/String04_StringCompression.java create mode 100644 3_Strings/String05_CountLowerCaseVowels.java create mode 100644 3_Strings/String06_Anagrams.java create mode 100644 3_Strings/String07_ValidPalindrome.java create mode 100644 3_Strings/String08_LongestCommonPrefix.java create mode 100644 3_Strings/String10_LongestCommonPrefix.java create mode 100644 3_Strings/String13_FirstOccurrenceInAString.class diff --git a/3_Strings/String01_PalindromeBasic.java b/3_Strings/String01_PalindromeBasic.java new file mode 100644 index 0000000..19696a3 --- /dev/null +++ b/3_Strings/String01_PalindromeBasic.java @@ -0,0 +1,22 @@ +public class String01_PalindromeBasic { + + public static boolean isPalindrome(String str) { //TC -> O(n) + int n = str.length(); + for(int i = 0; i < n/2; i++) { + if(str.charAt(i) != str.charAt(n-i-1)) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + String str1 = "racecar"; + String str2 = "noon"; + String str3 = "arghya"; + + System.out.println("is string palindrome?(true/false)"); + System.out.println(">> "+isPalindrome(str1)); + + } +} diff --git a/3_Strings/String02_ShortestPath.java b/3_Strings/String02_ShortestPath.java new file mode 100644 index 0000000..55f762a --- /dev/null +++ b/3_Strings/String02_ShortestPath.java @@ -0,0 +1,38 @@ +/* +Given a route containing 4 direction(E,W,N,S) find the shortest path to reach destination + */ + +public class String02_ShortestPath { + + public static double getShortestPath(String path) { //TC -> O(n) || n -> size of string + char direction; + int x = 0, y = 0; + for(int i = 0; i < path.length(); i++) { + direction = path.charAt(i); + if(direction == 'N'){ + y++; + } else if(direction == 'S') { + y--; + } else if(direction == 'E') { + x++; + } else if(direction == 'W') { + x--; + } + } + + return shortestPath(x,y); + } + public static double shortestPath(int x, int y) { //TC -> O(1) + double sum = x*x + y*y; + return Math.sqrt(sum); + } + + public static void main(String[] args) { + String path1 = "WNEENESENNN"; + String path2 = "SSEENNWW"; + + + System.out.println("Shortest Path >> "+ getShortestPath(path2)); + + } +} diff --git a/3_Strings/String03_UpperCase.java b/3_Strings/String03_UpperCase.java new file mode 100644 index 0000000..dc7331e --- /dev/null +++ b/3_Strings/String03_UpperCase.java @@ -0,0 +1,30 @@ +/* +For a given String convert each the first letter of each word to uppercase + */ + +public class String03_UpperCase { + + public static String toUpperCase(String str) { //TC -> O(n) || n -> size of the string + StringBuilder sb = new StringBuilder(""); + + char ch = Character.toUpperCase((str.charAt(0))); + sb.append(ch); + + for(int i = 1; i < str.length(); i++) { + if(str.charAt(i) == ' ' && i < str.length()-1) { + sb.append(str.charAt(i)); + i++; + sb.append(Character.toUpperCase(str.charAt(i))); + } else { + sb.append(str.charAt(i)); + } + } + + return sb.toString(); + } + + public static void main(String[] args) { + String str1 = "hii, I am arghya"; + System.out.println(toUpperCase(str1)); + } +} diff --git a/3_Strings/String04_StringCompression.java b/3_Strings/String04_StringCompression.java new file mode 100644 index 0000000..730e1e1 --- /dev/null +++ b/3_Strings/String04_StringCompression.java @@ -0,0 +1,42 @@ +/* +String compression + +Example 1: + string = "aaabbccdd" + output : "a3b2c3d2" + +Example 2: + string = "aaaabbbdd" + output : "a4b3d2" + +Example 1: + string = "abc" + output : "abc" + */ + +public class String04_StringCompression { + + public static String compress(String str) { //TC -> O(n) || n -> size of string + StringBuilder sb = new StringBuilder(""); + for(int i = 0; i < str.length(); i++) { + Integer count = 1; + while(i < str.length()-1 && str.charAt(i) == str.charAt(i+1)) { + count++; + i++; + } + sb.append(str.charAt(i)); + if(count > 1) { + sb.append(count); + } + } + return sb.toString(); + } + + public static void main(String[] args) { + String str1 = "aaabbccdd"; + String str2 = "aaaabbbdd"; + String str3 = "abc"; + + System.out.println(compress(str1)); + } +} diff --git a/3_Strings/String05_CountLowerCaseVowels.java b/3_Strings/String05_CountLowerCaseVowels.java new file mode 100644 index 0000000..8f203c8 --- /dev/null +++ b/3_Strings/String05_CountLowerCaseVowels.java @@ -0,0 +1,24 @@ +/* +Count how many times lowercase vowels occurred in a String entered. + */ +import java.util.Scanner; +public class String05_CountLowerCaseVowels { + + public static int countVowels(String str) { + int count = 0; + for(int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { + count++; + } + } + return count; + } + + public static void main(String[] args) { + Scanner scn = new Scanner(System.in); + System.out.print("Enter String >> "); + String str = scn.nextLine(); + System.out.println("---> "+countVowels(str)+" lowercase vowels."); + } +} diff --git a/3_Strings/String06_Anagrams.java b/3_Strings/String06_Anagrams.java new file mode 100644 index 0000000..c8f491c --- /dev/null +++ b/3_Strings/String06_Anagrams.java @@ -0,0 +1,74 @@ +/* +Determine if 2 Strings are anagrams of each other. +What are anagrams? +If two strings contain the same characters but in a different order, they can be said to be anagrams. Consider race and care. In this case, race's characters can be formed into a study, or care's characters can be formed into race. Below is a java program to check if two strings are anagrams or not. + +Ex1: + str1 = "anagram" str2 = "nagaram" + >> true + +Ex2: + str1 = "rat" str2 = "cat" + >> false + +Ex1: + str1 = "race" str2 = "ace" + >> false + +Ex1: + str1 = "aacc" str2 = "ccac" + >> false + + */ + +public class String06_Anagrams { +/* NOTE >> this code will give a wrong ans on --> str1 = "aacc" str2 = "ccac" , for this original ans will be "false", but this code will give ans true + public static boolean isAnagrams(String str1, String str2) { + if(str1.length() == str2.length()) { // --> checking for equal length + for(int i = 0; i < str1.length(); i++) { + char ch = str1.charAt(i); + int j = 0; + while(j < str2.length() && ch != str2.charAt(j)) { //--> checking for + j++; + } + if(j < str2.length()) { + continue; + } else { + return false; + } + } + return true; + } else { + return false; + } + } +*/ + + public static boolean isAnagrams(String str1, String str2) { //TC -> O(n) | SC -> O(26) == O(1) //n -> length of the string + if(str1.length() != str2.length()) { //--> checking for equal length + return false; + } + + int[] freq = new int[26]; //--> to count frequency of every character + + for(int i = 0; i < str1.length(); i++) { + freq[Character.toLowerCase(str1.charAt(i)) - 'a']++; + freq[Character.toLowerCase(str2.charAt(i)) - 'a']--; + } + + for(int i = 0; i < 26; i++) { + if(freq[i] != 0) { //--> 0 means both sting have same numbers of characters + return false; + } + } + + return true; + } + + + public static void main(String[] args) { + String str1 = "aacc", str2 = "ccac"; + + System.out.println(isAnagrams(str1, str2)); + } +} diff --git a/3_Strings/String07_ValidPalindrome.java b/3_Strings/String07_ValidPalindrome.java new file mode 100644 index 0000000..9fa4bc7 --- /dev/null +++ b/3_Strings/String07_ValidPalindrome.java @@ -0,0 +1,61 @@ +/* +A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. +Given a string s, return true if it is a palindrome, or false otherwise. + +Example 1: +Input: s = "A man, a plan, a canal: Panama" +Output: true +Explanation: "amanaplanacanalpanama" is a palindrome. + +Example 2: +Input: s = "race a car" +Output: false +Explanation: "raceacar" is not a palindrome. + +Example 3: +Input: s = " " +Output: true +Explanation: s is an empty string "" after removing non-alphanumeric characters. +Since an empty string reads the same forward and backward, it is a palindrome. + +Constraints: + 1 <= s.length <= 2 * 105 + s consists only of printable ASCII characters. + */ + +public class String07_ValidPalindrome { + + public static boolean isPalindrome(String str) { //TC -> O(n) || SC -> O(1) //--> n = length of the string + int startIndex = 0, endIndex = str.length()-1; + while(startIndex < endIndex) { + //----when there is a space----// + if(!Character.isLetterOrDigit(str.charAt(startIndex))) { + startIndex++; + continue; // --> back to starting of the loop + } + if(!Character.isLetterOrDigit(str.charAt(endIndex))) { + endIndex--; + continue; // --> back to starting of the loop + } + //---- ----// + if(Character.toLowerCase(str.charAt(startIndex)) != Character.toLowerCase(str.charAt(endIndex))) { + return false; //--> whenever both character does not match + } + + startIndex++; + endIndex--; + } + + return true; //--> when loop ends completely + } + + public static void main(String[] args) { + String str1 = "A man, a plan, a canal: Panama"; + String str2 = "race a car"; + String str3 = " "; + // String str4 = "A Man 4 aba 4 nama"; + // String str5 = "raceaecar"; + + System.out.println("is String is Palindrome?(true/false) \n>> " + isPalindrome(str2)); + } +} \ No newline at end of file diff --git a/3_Strings/String08_LongestCommonPrefix.java b/3_Strings/String08_LongestCommonPrefix.java new file mode 100644 index 0000000..cc30b58 --- /dev/null +++ b/3_Strings/String08_LongestCommonPrefix.java @@ -0,0 +1,26 @@ +/* +Write a function to find the longest common prefix string amongst an array of strings. +If there is no common prefix, return an empty string "". + +Example 1: +Input: strs = ["flower","flow","flight"] +Output: "fl" + +Example 2: +Input: strs = ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. + +Constraints: + 1 <= strs.length <= 200 + 0 <= strs[i].length <= 200 + strs[i] consists of only lowercase English letters. + */ + +public class String08_LongestCommonPrefix { + public static void main(String[] args) { + String str = "Arghya"; + System.out.println(str.substring(0,3)); + + } +} \ No newline at end of file diff --git a/3_Strings/String10_LongestCommonPrefix.java b/3_Strings/String10_LongestCommonPrefix.java new file mode 100644 index 0000000..5e51163 --- /dev/null +++ b/3_Strings/String10_LongestCommonPrefix.java @@ -0,0 +1,58 @@ +/* +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". + + + +Example 1: + +Input: strs = ["flower","flow","flight"] +Output: "fl" + +Example 2: + +Input: strs = ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. + + + +Constraints: + + 1 <= strs.length <= 200 + 0 <= strs[i].length <= 200 + strs[i] consists of only lowercase English letters. + + + */ + +import java.util.Arrays; + +public class String10_LongestCommonPrefix { + + public static String lcp(String[] str) { //TC -> O(n*log(n)) + Arrays.sort(str); + String s1 = str[0]; + String s2 = str[str.length-1]; + + int i = 0; + + while(i < s1.length() && i < s2.length()) { + if(s1.charAt(i) == s2.charAt(i)) { + i++; + } else { + break; + } + } + + return s1.substring(0, i); + + } + + public static void main(String[] args) { + String[] str1 = {"flower","flow","flight"}; + + System.out.println(lcp(str1)); + } +} diff --git a/3_Strings/String13_FirstOccurrenceInAString.class b/3_Strings/String13_FirstOccurrenceInAString.class new file mode 100644 index 0000000000000000000000000000000000000000..3b08c06a23195b8b021d4697ff552465179ab9a4 GIT binary patch literal 1044 zcmah|S#Q%o5dOAKW5;!`^x}wnw>f&G7iZd(7E~!xOOc8y0T0x1R>j3}f)6C#`4hbI z(idLfAw?kZ1NZ~{7bK2ZyHy)f30a<BiA;uJp zE0{=N5>qm!RVdIEq{W(1(Sxkeazf0gn8looc^P?z_^Rbtevv`SWcL|j_iGi-(7kOr z{9#ZnbN8`Pw#gIse0R@x8Pb{UBjdG^w+-hoPaexTEVO#EC5FyD-!Nb981++#SkpNalW$of-*g1Mxcq#}ay@_7Gy~V=j>${TMzl3AXlO{HPsW0VMJ#Dp z#)^g;xXGZ{ocm^24C69xX}FC$3`75N-wZ6f!l^E)SRB=G7X=N27!um5hBXvrtZTT3 z4TiD*Qex;i$KNd&a8i?Hd`sDu}ky|9y_JEc;#wLf%*zX}Z7V;HzN zfG9~J`?NXF8_(xeg0BTcU?76CYWYVrEuTnmqgo(Dqh9Aug<54R!ct&U+V|0&u=>-51m>4|CezJ608LjQP z6R?k@5CX|~=o~^q43u;c>LErSu++9D74=*LZ8P*&Vh8Urn$vY*95f)&8hZytUpq$P zt;CN1{78MEQ*9ycFl5rNk(D9}I;QCPr7?mW*$WuQ72559^b0Y@rhcNG2wbJ`h`<9% zFHyi`vVA)l-}wajE0iZENF>z;I%Z}+Lu;V3fvyI+&r9hF&rDNEX-ptPSl2^3slQMc B?zaE{ literal 0 HcmV?d00001 From a251ed9f7f787577b27011f2fef3c27b434a8b97 Mon Sep 17 00:00:00 2001 From: Arghya Das <95538110+alfaArghya@users.noreply.github.com> Date: Mon, 26 Jun 2023 12:02:11 +0530 Subject: [PATCH 4/4] Add files via upload --- 1_Arrays/Array01_MaxAndMiniElement.java | 45 +++++++ 1_Arrays/Array02_ReverseArray.java | 64 ++++++++++ 1_Arrays/Array03_MaximumSumSubArray.java | 56 ++++++++ 1_Arrays/Array04_DuplicateValues.java | 40 ++++++ .../Array05_ChocolateDistributionProblem.java | 74 +++++++++++ .../Array06_SearchRotatedSortedArray.java | 120 ++++++++++++++++++ 1_Arrays/Array07_NextPermutation.java | 102 +++++++++++++++ 1_Arrays/Array08_BestTime2BuyAndSell.java | 47 +++++++ 1_Arrays/Array09_RepeatAndMissingNumber.java | 71 +++++++++++ 1_Arrays/Array10_TrappingRainWater.java | 53 ++++++++ 1_Arrays/Array11_RemoveDuplicate.java | 67 ++++++++++ .../Array12_ProductOfArrayExceptSelf.java | 59 +++++++++ 1_Arrays/Array13_MaximumProductSubArray.java | 44 +++++++ .../Array14_MinimumInSortedRotatedArray.java | 66 ++++++++++ 1_Arrays/Array15_ContainerWithMostWater.java | 46 +++++++ 1_Arrays/Array16_GivenSumPair.java | 63 +++++++++ ...7_MergeOperationToMakeArrayPalindrome.java | 35 +++++ 1_Arrays/Array18_MoveZeros.java | 53 ++++++++ 1_Arrays/Array19_RunningSum.java | 48 +++++++ 1_Arrays/Array20_FindPivotIndex.java | 63 +++++++++ 1_Arrays/Array21_MajorityElement.java | 57 +++++++++ 1_Arrays/Array22_FibonacciNumber.java | 40 ++++++ 1_Arrays/Array23_SquareOfSortedArray.java | 54 ++++++++ 1_Arrays/Array24_PascalTriangle.java | 46 +++++++ 1_Arrays/Array25_SpiralMatrix.java | 63 +++++++++ 1_Arrays/Array26_RotateImage.java | 55 ++++++++ 1_Arrays/Array27_DiagonalSum.java | 34 +++++ 1_Arrays/Array28_2Sum.java | 71 +++++++++++ 1_Arrays/Array29_3Sum.java | 77 +++++++++++ 1_Arrays/Array31_SubArraySumEqualsK.java | 44 +++++++ 1_Arrays/Array33_4Sum.java | 71 +++++++++++ 31 files changed, 1828 insertions(+) create mode 100644 1_Arrays/Array01_MaxAndMiniElement.java create mode 100644 1_Arrays/Array02_ReverseArray.java create mode 100644 1_Arrays/Array03_MaximumSumSubArray.java create mode 100644 1_Arrays/Array04_DuplicateValues.java create mode 100644 1_Arrays/Array05_ChocolateDistributionProblem.java create mode 100644 1_Arrays/Array06_SearchRotatedSortedArray.java create mode 100644 1_Arrays/Array07_NextPermutation.java create mode 100644 1_Arrays/Array08_BestTime2BuyAndSell.java create mode 100644 1_Arrays/Array09_RepeatAndMissingNumber.java create mode 100644 1_Arrays/Array10_TrappingRainWater.java create mode 100644 1_Arrays/Array11_RemoveDuplicate.java create mode 100644 1_Arrays/Array12_ProductOfArrayExceptSelf.java create mode 100644 1_Arrays/Array13_MaximumProductSubArray.java create mode 100644 1_Arrays/Array14_MinimumInSortedRotatedArray.java create mode 100644 1_Arrays/Array15_ContainerWithMostWater.java create mode 100644 1_Arrays/Array16_GivenSumPair.java create mode 100644 1_Arrays/Array17_MergeOperationToMakeArrayPalindrome.java create mode 100644 1_Arrays/Array18_MoveZeros.java create mode 100644 1_Arrays/Array19_RunningSum.java create mode 100644 1_Arrays/Array20_FindPivotIndex.java create mode 100644 1_Arrays/Array21_MajorityElement.java create mode 100644 1_Arrays/Array22_FibonacciNumber.java create mode 100644 1_Arrays/Array23_SquareOfSortedArray.java create mode 100644 1_Arrays/Array24_PascalTriangle.java create mode 100644 1_Arrays/Array25_SpiralMatrix.java create mode 100644 1_Arrays/Array26_RotateImage.java create mode 100644 1_Arrays/Array27_DiagonalSum.java create mode 100644 1_Arrays/Array28_2Sum.java create mode 100644 1_Arrays/Array29_3Sum.java create mode 100644 1_Arrays/Array31_SubArraySumEqualsK.java create mode 100644 1_Arrays/Array33_4Sum.java diff --git a/1_Arrays/Array01_MaxAndMiniElement.java b/1_Arrays/Array01_MaxAndMiniElement.java new file mode 100644 index 0000000..8b83ec9 --- /dev/null +++ b/1_Arrays/Array01_MaxAndMiniElement.java @@ -0,0 +1,45 @@ +/* +Q. Given an array of size N. The task is to find the maximum and the minimum element of the array using the minimum number of comparisons. + +Examples: + Input: arr[] = {3, 5, 4, 1, 9} + Output: Minimum element is: 1 + Maximum element is: 9 + + Input: arr[] = {22, 14, 8, 17, 35, 3} + Output: Minimum element is: 3 + Maximum element is: 35 +*/ + +public class Array01_MaxAndMiniElement{ + + //search for maximum element in array + public static int maxElement(int arr[]){ //TC -> O(n) + int max = Integer.MIN_VALUE; //take minimum value such as -infinity + for(int i = 0; i < arr.length; i++){ + if(arr[i] > max){ //compare + max = arr[i]; + } + } + return max; + } + + //search for minimum element in a array + public static int minElement(int arr[]){ //TC -> O(n) + int min = Integer.MAX_VALUE; //take maximum value such as +infinity + for(int i = 0; i < arr.length; i++){ + if(arr[i] < min){ //compare + min = arr[i]; + } + } + return min; + } + public static void main(String args[]){ + int arr1[] = {3, 5, 4, 1, 9}; + int arr2[] = {22, 14, 8, 17, 35, 5}; + int arr3[] = {1000, 11, 445, 1, 330, 3000}; + int arr[] = {1000, 11, 445, 1, 330, 3000, 3, 5, 4, 1, 9, 22, 14, 8, 17, 35, 5}; + System.out.println("Maximum element -> "+ maxElement(arr)); + System.out.println("Minimum element -> "+ minElement(arr)); + } +} \ No newline at end of file diff --git a/1_Arrays/Array02_ReverseArray.java b/1_Arrays/Array02_ReverseArray.java new file mode 100644 index 0000000..4e6418e --- /dev/null +++ b/1_Arrays/Array02_ReverseArray.java @@ -0,0 +1,64 @@ +/* +Q. Given an array (or string), the task is to reverse the array/string. +Examples :  +Input : arr[] = {1, 2, 3} +Output : arr[] = {3, 2, 1} + +Input : arr[] = {4, 5, 1, 2} +Output : arr[] = {2, 1, 5, 4} + */ + +public class Array02_ReverseArray { + /*----Approach 1 --> Iterative way ----*/ + public static void reverseArray(int arr[]){ //TC -> O(n) + int startIndex = 0; //always start from index 0 + int endIndex = arr.length-1; //array have 0 to n-1 index & n is the size of array + while(startIndex < endIndex){ + //swap + int temp = arr[startIndex]; + arr[startIndex] = arr[endIndex]; + arr[endIndex] = temp; + + //change index + startIndex++; + endIndex--; + } + + } + /*---- ----*/ + /*----Approach 2 --> recursive way ----*/ + public static void reverseArray(int arr[], int startIndex, int endIndex){ //TC -> O(n) + //base case + if(startIndex >= endIndex){ + return; + } + //swap + int temp = arr[startIndex]; + arr[startIndex] = arr[endIndex]; + arr[endIndex] = temp; + + //calling recursive function + reverseArray(arr, startIndex+1, endIndex-1); + } + /*---- ----*/ + //print array + public static void printArray(int arr[]){ + for(int i = 0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + } + + public static void main(String args[]){ + int arr1[] = {1, 2, 3} , arr2[] = {4, 5, 1, 2}; + int arr[] = {1, 2, 3, 4, 5, 1, 2}; + System.out.print("original Array -> "); + printArray(arr2); + + reverseArray(arr2); + // reverseArray(arr, 0, arr.length-1); + + System.out.print("new Array -> "); + printArray(arr2); + } +} diff --git a/1_Arrays/Array03_MaximumSumSubArray.java b/1_Arrays/Array03_MaximumSumSubArray.java new file mode 100644 index 0000000..4f45836 --- /dev/null +++ b/1_Arrays/Array03_MaximumSumSubArray.java @@ -0,0 +1,56 @@ +/* +Given an integer array nums, find the subarray with the largest sum, and return its sum. + +Example 1: +Input: nums = [-2,1,-3,4,-1,2,1,-5,4] +Output: 6 +Explanation: The subarray [4,-1,2,1] has the largest sum 6. + +Example 2: +Input: nums = [1] +Output: 1 +Explanation: The subarray [1] has the largest sum 1. + +Example 3: +Input: nums = [5,4,-1,7,8] +Output: 23 +Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.  + +Constraints: + 1 <= nums.length <= 105 + -104 <= nums[i] <= 104 + + +Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. + + */ + +public class Array03_MaximumSumSubArray { + + /*---- kadaen's method ----*/ + public static int maxSumOfSubArray(int arr[]){ + //step 1 -> initialize values + int currSum = 0; + int maxSum = Integer.MIN_VALUE; //it refers to -infinity + + //step 2 -> run a loop and do work + for(int i = 0; i < arr.length; i++){ + currSum += arr[i];//sum + if(currSum <= 0){ //if current sum less then 0, then reassigned the value 0 to current sum + currSum = 0; + } + if(maxSum < currSum){ //compare current sum and maximum sum + maxSum = currSum; + } + } + + return maxSum; + } + + public static void main(String[] args) { + int nums1[] = {-2,1,-3,4,-1,2,1,-5,4}; + int nums2[] = {1}; + int nums3[] = {5,4,-1,7,8}; + System.out.println("Maximum sum SubArray -> "+maxSumOfSubArray(nums3)); + } +} diff --git a/1_Arrays/Array04_DuplicateValues.java b/1_Arrays/Array04_DuplicateValues.java new file mode 100644 index 0000000..bf56b48 --- /dev/null +++ b/1_Arrays/Array04_DuplicateValues.java @@ -0,0 +1,40 @@ +/* +Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. + +Example 1: +Input: nums = [1,2,3,1] +Output: true + +Example 2: +Input: nums = [1,2,3,4] +Output: false + +Example 3: +Input: nums = [1,1,1,3,3,4,3,2,4,2] +Output: true + +Constraints: + 1 <= nums.length <= 105 + -109 <= nums[i] <= 109 + */ + +public class Array04_DuplicateValues { + + public static boolean checkDuplicate(int nums[]){ //TC -> O(n^2) + for(int i = 0; i < nums.length-1; i++){ + for(int j = i+1; j O(n*log(n)) + //step 1 -> sort the array(we can use java in build sorting algo <> we can make our own sorting algo) + Arrays.sort(arr); //java built in sort + // bubbleSort(arr); //we can also use .... user defined sorting instate of build in sort + //step 2 -> initialize +infinity & run a loop + int minDiff = Integer.MAX_VALUE; //+infinity + for(int i = 0; i < arr.length; i++){ + //step 3 -> difference between maximum and minimum + int diff = arr[i+m-1]-arr[i]; + //step 4 -> compare + if(minDiff > diff){ + minDiff = diff; + } + //corner case -> this will stop the loop + if((i+m-1) >= arr.length-1){ + break; + } + } + + return minDiff; + } + /*---- Bubble Sort algo ----*/ + public static void bubbleSort(int arr[]){ + for(int i = 0; i < arr.length-1; i++){ + int track = 0; + for(int j = 0; j < arr.length-1-i; j++){ + if(arr[j] > arr[j+1]){ + //swap + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + track++; + } + } + if(track == 0){ + break; + } + } + } + /*---- ----*/ + + public static void main(String args[]){ + int arr1[] = {7, 3, 2, 4, 9, 12, 56}; + int arr2[] = {3, 4, 1, 9, 56, 7, 9, 12}; + int arr3[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50}; + int arr_worstCase[] = {32,24,15,46,52,57,5,39}; + + System.out.println("Minimum difference -> "+minDiff(arr_worstCase, 2)); + + + } +} diff --git a/1_Arrays/Array06_SearchRotatedSortedArray.java b/1_Arrays/Array06_SearchRotatedSortedArray.java new file mode 100644 index 0000000..ff4e08a --- /dev/null +++ b/1_Arrays/Array06_SearchRotatedSortedArray.java @@ -0,0 +1,120 @@ +/* +There is an integer array nums sorted in ascending order (with distinct values). +Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. + +Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. + +You must write an algorithm with O(log n) runtime complexity. + +Example 1: +Input: nums = [4,5,6,7,0,1,2], target = 0 +Output: 4 + +Example 2: +Input: nums = [4,5,6,7,0,1,2], target = 3 +Output: -1 + +Example 3: +Input: nums = [1], target = 0 +Output: -1 + +Constraints: + 1 <= nums.length <= 5000 + -104 <= nums[i] <= 104 + All values of nums are unique. + nums is an ascending array that is possibly rotated. + -104 <= target <= 104 + */ + +public class Array06_SearchRotatedSortedArray { + /*---- iterative method ----*/ + public static int searchTarget(int arr[], int target){ + + int startIndex = 0; + int endIndex = arr.length-1; + + while(startIndex <= endIndex){ //when startIndex is greater than endIndex our loop will stop running + //step 1 -> find out mid + int midIndex = startIndex+(endIndex - startIndex)/2; + //step 2 -> when target at midIndex + if(arr[midIndex] == target){ + return midIndex; + } + //step 3 + //Case 1 -> mid lies on Line1 + if(arr[startIndex] <= arr[midIndex]){ + //when target lies left side of Line1 + if(arr[startIndex] <= target && target <= arr[midIndex]){ + endIndex = midIndex-1; + } + //when target lies right side of Line1(that's mean half of Line1 and whole Line2) + else{ + startIndex = midIndex+1; + } + } + //case 2 -> mid lies on Line2 + else{ + //when target lies right side of Line2 + if(arr[midIndex] <= target && target <= arr[endIndex]){ + startIndex = midIndex+1; + } + //when target lies left side of Line2(that's mean half of Line2 and whoLe Line1) + else{ + endIndex = midIndex+1; + } + } + } + + return -1; //when target is not there in array + } + /*---- ----*/ + + /*---- recursive method ----*/ + public static int searchTarget(int arr[], int target, int startIndex, int endIndex){ //TC -> O(log n) + //base case + if(startIndex > endIndex){ + return -1; //when target is not there in array + } + //step 1 -> find out mid + int midIndex = startIndex+(endIndex-startIndex)/2; + //step 2 -> when target at midIndex + if(arr[midIndex] == target){ + return midIndex; + } + //step 3 + //Case 1 -> mid lies on Line1 + if(arr[startIndex] <= arr[midIndex]){ + //when target lies left side of Line1 + if(arr[startIndex] <= target && target <= arr[midIndex]){ + return searchTarget(arr, target, startIndex, midIndex-1); + } + //when target lies right side of Line1(that's mean half of Line1 and whole Line2) + else{ + return searchTarget(arr, target, midIndex+1, endIndex); + } + } + //case 2 -> mid lies on Line2 + else{ + //when target lies right side of Line2 + if(arr[midIndex] <= target && target <= arr[endIndex]){ + return searchTarget(arr, target, midIndex + 1, endIndex); + } + //when target lies left side of Line2(that's mean half of Line2 and whoLe Line1) + else{ + return searchTarget(arr, target, startIndex, midIndex); + } + } + } + /*---- ----*/ + + public static void main(String args[]) { + int nums[] = {4,5,6,7,0,1,2}; + int result = searchTarget(nums, 6); + if(result == -1){ + System.out.println("Your targe is not in the array"); + } + else{ + System.out.println("target found at index "+result); + } + } +} diff --git a/1_Arrays/Array07_NextPermutation.java b/1_Arrays/Array07_NextPermutation.java new file mode 100644 index 0000000..d6ed969 --- /dev/null +++ b/1_Arrays/Array07_NextPermutation.java @@ -0,0 +1,102 @@ +/* +A permutation of an array of integers is an arrangement of its members into a sequence or linear order. +For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. + +The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). + + For example, the next permutation of arr = [1,2,3] is [1,3,2]. + Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. + While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. + +Given an array of integers nums, find the next permutation of nums. + +The replacement must be in place and use only constant extra memory. + +Example 1: +Input: nums = [1,2,3] +Output: [1,3,2] + +Example 2: +Input: nums = [3,2,1] +Output: [1,2,3] + +Example 3: +Input: nums = [1,1,5] +Output: [1,5,1] + +  + +Constraints: + 1 <= nums.length <= 100 + 0 <= nums[i] <= 100 + + */ + +public class Array07_NextPermutation { + + public static void nextPermutation (int[] arr) { //TC -> O(n) + int sizeOfArray = arr.length-1; + int pivotPoint = 0; + //find out pivot point + for(int i = sizeOfArray-1; i >= 0; i--) { + if(arr[i] < arr[i+1]) { + pivotPoint = i; + break; + } + } + + if( pivotPoint == 0) { //when we don't find out any pivot point in array.....that's mean array is in descending order --> reverse whole array + reverseArray(arr, 0, sizeOfArray); + } else { //when we find out our pivot point --> find out right most successor of pivot in suffix + int successor = 0; + for(int i = sizeOfArray; i > pivotPoint; i--) { + if(arr[i] > arr[pivotPoint]) { + successor = i; + break; + } + } + + //swap -> pivotPoint and successor + int temp = arr[pivotPoint]; + arr[pivotPoint] = arr[successor]; + arr[successor] = temp; + + //reverse in range of successor+1 to arr.length-1 + reverseArray(arr, pivotPoint+1, sizeOfArray); + } + + } + + //reverse in range + public static void reverseArray(int[] arr, int startIndex, int endIndex) { + while(startIndex < endIndex) { + int temp = arr[startIndex]; + arr[startIndex] = arr[endIndex]; + arr[endIndex] = temp; + + startIndex++; + endIndex--; + } + } + + //print the array + public static void printArray(int[] arr) { + for(int i = 0; i < arr.length; i++) { + System.out.print(arr[i]+" "); + } + System.out.println("\n--------------------------"); + } + + public static void main(String[] args) { + int[] arr1 = {1,2,3}; + int[] arr2 = {3,2,1}; + int[] arr3 = {1,1,5}; + int[] arr4 = {2,4,1,7,5,0}; + int[] arr5 = {1,2,3,6,5,4}; + + System.out.print("Next permutation -> "); + nextPermutation(arr5); + printArray(arr5); + + } +} diff --git a/1_Arrays/Array08_BestTime2BuyAndSell.java b/1_Arrays/Array08_BestTime2BuyAndSell.java new file mode 100644 index 0000000..4577a36 --- /dev/null +++ b/1_Arrays/Array08_BestTime2BuyAndSell.java @@ -0,0 +1,47 @@ +/* +You are given an array prices where prices[i] is the price of a given stock on the ith day. +You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. +Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + +Example 1: + Input: prices = [7,1,5,3,6,4] + Output: 5 + Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. +Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. + +Example 2: + Input: prices = [7,6,4,3,1] + Output: 0 +Explanation: In this case, no transactions are done and the max profit = 0. + +Constraints: + + 1 <= prices.length <= 105 + 0 <= prices[i] <= 104 + +*/ + +public class Array08_BestTime2BuyAndSell { + + public static int maxProfit (int[] price) { //TC -> O(n) + int buyPrice = Integer.MAX_VALUE, maxProfit = 0; + + for(int i = 0; i < price.length; i++) { + if(buyPrice < price[i]) { //when our buying price is less than current day price ...... on that day we may be sell the stock --> we can calculate our maxProfit + int profit = price[i] - buyPrice; + maxProfit = Math.max(maxProfit, profit); + } else { //but when our buyPrice is greater than current day price...... we only can buy the stock + buyPrice = price[i]; + } + } + + return maxProfit; + } + + public static void main(String[] args) { + int[] arr1 = {7,1,5,3,6,4}; + int[] arr2 = {7,6,4,3,1}; + + System.out.println("Maximum profit >> "+maxProfit(arr1)); + } +} \ No newline at end of file diff --git a/1_Arrays/Array09_RepeatAndMissingNumber.java b/1_Arrays/Array09_RepeatAndMissingNumber.java new file mode 100644 index 0000000..17b4cd9 --- /dev/null +++ b/1_Arrays/Array09_RepeatAndMissingNumber.java @@ -0,0 +1,71 @@ +import java.util.Arrays; + +/* +Given an unsorted array of size n. Array elements are in the range of 1 to n. One number from set {1, 2, …n} is missing and one number occurs twice in the array. Find these two numbers. + +Examples: + + Input: arr[] = {3, 1, 3} + Output: Missing = 2, Repeating = 3 + Explanation: In the array, 2 is missing and 3 occurs twice + + Input: arr[] = {4, 3, 6, 2, 1, 1} + Output: Missing = 5, Repeating = 1 + + */ + +public class Array09_RepeatAndMissingNumber { + + /*---- Approach 1 -> TC -> O(n) | SC -> O(n) ----*/ + public static void repeatingAndMissingNumber1(int[] arr) { + int n = arr.length; //size of array + int[] temp = new int[n]; + + for(int i = 0; i < n; i++) { + temp[arr[i]-1]++; //for every value in array increase by 1 in (array[i]-1) location of temp array + } + + for(int i = 0; i < n; i++) { + if(temp[i] > 1) { //if any value is greater than 1...that's mean duplicate value is index+1 + System.out.println("Repeating Number >> " + (i+1)); + } + if( temp[i] < 1) { //if any value is less than 1 or 0......that's mean index+1 is missing value + System.out.println("Missing number >> "+ (i+1)); + } + } + } + /*---- ----*/ + + /*---- Approach 2 -> TC -> O(n*log(n)) | SC -> O(1) ----*/ + public static void repeatingAndMissingNumber2(int[] arr) { + Arrays.sort(arr); //java in-build array...... TC -> O(n*log(n)) + + int n = arr.length; //Size of array + for(int i = 0; i < n-1; i++) { + if(arr[i] == arr[i+1]) { //if current element and it's next element is equal..... that's mean ith element is repeating + System.out.println("Repeating Number >> "+arr[i]); + } + } + + int temp = 0; + for(int i = 0; i < n; i++) { + if(arr[i] - temp > 1) { //if current element - temp(previous element) is greater than 1..... that's mean there is a gap(means a missing element) + System.out.println("Missing Number >> "+(temp+1)); + } + temp = arr[i]; + } + } + /*---- ----*/ + + + + public static void main(String[] args) { + int[] arr1 = {3,1,3}; + int[] arr2 = {4,3,6,2,1,1}; + int[] arr3 = {7,3,4,5,5,6,2}; + + repeatingAndMissingNumber1(arr2); + System.out.println("--------------------------"); + repeatingAndMissingNumber2(arr2); + } +} diff --git a/1_Arrays/Array10_TrappingRainWater.java b/1_Arrays/Array10_TrappingRainWater.java new file mode 100644 index 0000000..9c5007d --- /dev/null +++ b/1_Arrays/Array10_TrappingRainWater.java @@ -0,0 +1,53 @@ +/* +Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. + +Example 1: +Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] +Output: 6 +Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. + +Example 2: +Input: height = [4,2,0,3,2,5] +Output: 9 + + */ + +public class Array10_TrappingRainWater { + + public static int totalWater(int[] height) { + int n = height.length; + + //calculate left max boundary + int[] leftMaxBoundary = new int[n]; + leftMaxBoundary[0] = height[0]; //always first bar height is leftMaxBoundary for first bar + for(int i = 1; i < n; i++) { //store from left side + leftMaxBoundary[i] = Math.max(height[i], leftMaxBoundary[i-1]); + } + + //calculate right max boundary + int[] rightMaxBoundary = new int[n]; + rightMaxBoundary[n-1] = height[n-1]; //always last bar height is rightMaxBoundary for last bar + for(int i = n-2; i >= 0; i--) { //stores from right side + rightMaxBoundary[i] = Math.max(height[i], rightMaxBoundary[i+1]); + } + + //calculate total trapped water + int totalTrappedWater = 0; + for(int i = 0; i < n; i++) { + //water level = min(left side max height, right side max height) + int waterLV= Math.min(leftMaxBoundary[i], rightMaxBoundary[i]); //calculate the water level on a bar + //trapped water on a bar = water level - height + totalTrappedWater += (waterLV-height[i]); //to calculate area of water on a bar -> no need to multiple by 1....cause it gives same ans) + } + + return totalTrappedWater; + } + + public static void main(String[] args) { + int[] height1 = {0,1,0,2,1,0,1,3,2,1,2,1}; + int[] height2 = {4,2,0,3,2,5}; + int[] height3 = {4,2,0,6,3,2,5}; + + System.out.println("Total Trapped Water >> "+totalWater(height2)); + } +} diff --git a/1_Arrays/Array11_RemoveDuplicate.java b/1_Arrays/Array11_RemoveDuplicate.java new file mode 100644 index 0000000..13e6d78 --- /dev/null +++ b/1_Arrays/Array11_RemoveDuplicate.java @@ -0,0 +1,67 @@ +/* +Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. + +Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things: + Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. + Return k. +Custom Judge: +The judge will test your solution with the following code: + +int[] nums = [...]; // Input array +int[] expectedNums = [...]; // The expected answer with correct length + +int k = removeDuplicates(nums); // Calls your implementation + +assert k == expectedNums.length; +for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; +} + +If all assertions pass, then your solution will be accepted. + +Example 1: +Input: nums = [1,1,2] +Output: 2, nums = [1,2,_] +Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). + +Example 2: +Input: nums = [0,0,1,1,1,2,2,3,3,4] +Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] +Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). + +Constraints: + 1 <= nums.length <= 3 * 104 + -100 <= nums[i] <= 100 + nums is sorted in non-decreasing order. + */ +public class Array11_RemoveDuplicate { + + public static int solution(int[] nums) { //TC -> O(n) | SC -> O(1) + int count = 1; + for(int i = 0; i < nums.length-1; i++) { + if(nums[i] < nums[i+1]) { + nums[count] = nums[i+1]; + count++; + } + } + printArray(nums, count); + return count; + } + + public static void printArray(int[] arr, int count) { + for(int i = 0; i < count; i++){ + System.out.print(arr[i]+" "); + } + System.out.println(); + } + + public static void main(String[] args) { + int[] arr1 = {1,1,2}; + int[] arr2 = {0,0,1,1,1,2,2,3,3,4}; + + System.out.println("original numbers -> "+solution(arr2)); + + } +} diff --git a/1_Arrays/Array12_ProductOfArrayExceptSelf.java b/1_Arrays/Array12_ProductOfArrayExceptSelf.java new file mode 100644 index 0000000..18c4fd2 --- /dev/null +++ b/1_Arrays/Array12_ProductOfArrayExceptSelf.java @@ -0,0 +1,59 @@ +/* +Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. +The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. +You must write an algorithm that runs in O(n) time and without using the division operation. + +Example 1: +Input: nums = [1,2,3,4] +Output: [24,12,8,6] + +Example 2: +Input: nums = [-1,1,0,-3,3] +Output: [0,0,9,0,0] + +Constraints: + + 2 <= nums.length <= 105 + -30 <= nums[i] <= 30 + The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. + + */ + +public class Array12_ProductOfArrayExceptSelf { + + public static void product(int[] arr) { + int n = arr.length; //size of array + + int[] prefix = new int[n]; + prefix[0] = 1; //first element will be always 1 + for(int i = 1; i < n; i++) { //loop starts from first + prefix[i] = prefix[i-1]*arr[i-1]; //calculate prefix + } + + int[] suffix = new int[n]; + suffix[n-1] = 1; //last element will be always 1 + for(int i = n-2; i >= 0; i--) { //loop starts from last + suffix[i] = suffix[i+1]*arr[i+1]; //calculate suffix + } + + for(int i = 0; i < n; i++) { + arr[i] = prefix[i]*suffix[i]; //calculating the product + } + + System.out.print("Product of Array >> "); + printArray(arr); + } + + public static void printArray(int[] arr) { + for(int i = 0; i < arr.length; i++) { + System.err.print(arr[i] +" "); + } + } + + public static void main(String[] args) { + int[] arr1 = {1,2,3,4}; + int[] arr2 = {-1,1,0,-3,3}; + + product(arr1); + } +} diff --git a/1_Arrays/Array13_MaximumProductSubArray.java b/1_Arrays/Array13_MaximumProductSubArray.java new file mode 100644 index 0000000..6a9416d --- /dev/null +++ b/1_Arrays/Array13_MaximumProductSubArray.java @@ -0,0 +1,44 @@ +/* +Given an integer array nums, find a subarray that has the largest product, and return the product. +The test cases are generated so that the answer will fit in a 32-bit integer. + +Example 1: +Input: nums = [2,3,-2,4] +Output: 6 +Explanation: [2,3] has the largest product 6. + +Example 2: +Input: nums = [-2,0,-1] +Output: 0 +Explanation: The result cannot be 2, because [-2,-1] is not a subarray. + + */ + +public class Array13_MaximumProductSubArray { + + public static void maximumProduct(int[] arr) { + int max = arr[0], min = arr[0], ans = arr[0]; + + for(int i = 1; i < arr.length; i++) { + int temp = max; //store current max value for further calculation + + max = Math.max(arr[i], Math.max(max * arr[i], min * arr[i])); + min = Math.min(arr[i], Math.min(min * arr[i], temp * arr[i])); + + if(max > ans) { + ans = max; + } + } + + System.out.println("Maximum Product SubArray >> "+ans); + } + + public static void main(String[] args) { + int[] arr1 = {2,3,-2,4}; + int[] arr2 = {2,-5,-2,-4,3}; + int[] arr3 = {0,2}; + int[] arr4 = {-2,0,-1}; + + maximumProduct(arr2); + } +} \ No newline at end of file diff --git a/1_Arrays/Array14_MinimumInSortedRotatedArray.java b/1_Arrays/Array14_MinimumInSortedRotatedArray.java new file mode 100644 index 0000000..048cbe2 --- /dev/null +++ b/1_Arrays/Array14_MinimumInSortedRotatedArray.java @@ -0,0 +1,66 @@ +/* +Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: + + [4,5,6,7,0,1,2] if it was rotated 4 times. + [0,1,2,4,5,6,7] if it was rotated 7 times. + +Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. + +Given the sorted rotated array nums of unique elements, return the minimum element of this array. + +You must write an algorithm that runs in O(log n) time. + +Example 1: +Input: nums = [3,4,5,1,2] +Output: 1 +Explanation: The original array was [1,2,3,4,5] rotated 3 times. + +Example 2: +Input: nums = [4,5,6,7,0,1,2] +Output: 0 +Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. + +Example 3: +Input: nums = [11,13,15,17] +Output: 11 +Explanation: The original array was [11,13,15,17] and it was rotated 4 times. + +Constraints: + n == nums.length + 1 <= n <= 5000 + -5000 <= nums[i] <= 5000 + All the integers of nums are unique. + nums is sorted and rotated between 1 and n times. + */ + +public class Array14_MinimumInSortedRotatedArray { + + public static int minimum (int[] arr) { + if(arr[0] < arr[arr.length-1]) { //when array is only sorted not rotated + return arr[0]; + } else { //when array is sorted and rotated + int startIndex = 0, endIndex = arr.length-1; + while(startIndex < endIndex) { + int midIndex = startIndex+(endIndex-startIndex)/2; //calculating midIndex + + if(arr[midIndex] < arr[endIndex]) { //minimum value lies on left side of midIndex + endIndex = midIndex; //re-assigned endIndex + } else { //minimum value lies on the right side of midIndex + startIndex = midIndex+1; //re-assigned startIndex + } + } + return arr[startIndex]; + } + } + + public static void main(String[] args) { + int[] arr1 = {3,4,5,1,2}; + int[] arr2 = {4,5,6,7,0,1,2}; + int[] arr3 = {11,13,15,17}; + int[] arr4 = {5,1,2,3,4}; + int[] arr5 = {2,4,5,6,7,0}; + + System.out.println(minimum(arr3)); + + } +} diff --git a/1_Arrays/Array15_ContainerWithMostWater.java b/1_Arrays/Array15_ContainerWithMostWater.java new file mode 100644 index 0000000..77bd22e --- /dev/null +++ b/1_Arrays/Array15_ContainerWithMostWater.java @@ -0,0 +1,46 @@ +/* +You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). +Find two lines that together with the x-axis form a container, such that the container contains the most water. +Return the maximum amount of water a container can store. +Notice that you may not slant the container. + +Example 1: +Input: height = [1,8,6,2,5,4,8,3,7] +Output: 49 +Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. + +Example 2: +Input: height = [1,1] +Output: 1 + + */ + +public class Array15_ContainerWithMostWater { + + public static int mostWater(int[] arr) { //TC -> O(n) + int leftPoint = 0, rightPoint = arr.length-1; //two pointers + int maxWater = Integer.MIN_VALUE; + + while(leftPoint < rightPoint) { + int height = Math.min(arr[leftPoint], arr[rightPoint]); //water can store in minimum height + int width = rightPoint-leftPoint; //calculate width + int currentWater = height * width; //calculate current water + maxWater = Math.max(maxWater,currentWater); + + //changing pointers + if(arr[leftPoint] < arr[rightPoint]) { + leftPoint++; + } else { + rightPoint--; + } + } + + return maxWater; + } + + public static void main(String[] args) { + int[] arr1 = {1,8,6,2,5,4,8,3,7}; + + System.out.println("Maximum water can store >> "+mostWater(arr1)); + } +} diff --git a/1_Arrays/Array16_GivenSumPair.java b/1_Arrays/Array16_GivenSumPair.java new file mode 100644 index 0000000..c8338e5 --- /dev/null +++ b/1_Arrays/Array16_GivenSumPair.java @@ -0,0 +1,63 @@ +/* +Find if there is a pair with a given sum in the rotated sorted Array. +Given an array arr[] of distinct elements size N that is sorted and then around an unknown point, the task is to check if the array has a pair with a given sum X. + +Examples : + + Input: arr[] = {11, 15, 6, 8, 9, 10}, X = 16 + Output: true + Explanation: There is a pair (6, 10) with sum 16 + + Input: arr[] = {11, 15, 26, 38, 9, 10}, X = 35 + Output: true + Explanation: There is a pair (26, 9) with sum 35 + + Input: arr[] = {11, 15, 26, 38, 9, 10}, X = 45 + Output: false + Explanation: There is no pair with sum 45. + + */ + +public class Array16_GivenSumPair { + + public static boolean isSumPair(int[] arr, int X) { //TC -> O(n) || SC -> O(1) + int n = arr.length; //size of array + int p = 0, pNext = 0; + //run a loop to find out pivot point + for(int i = 0; i < n-1; i++) { + if(arr[i] > arr[i+1]) { + p = i; + pNext = i+1; + break; + } + } + + //now find out the ans + while(p != pNext) { + int sum = arr[p] + arr[pNext]; + + if(sum > X) { + p = (n+p-1) % n; //change the pivot point + } else if(sum < X) { + pNext = (pNext+1) % n; //change pivotNext point + } else { + return true; //when sum and X are equal + } + } + + return false; //when all pairs dose not equal to X + } + public static void main(String[] args) { + int[] arr1 = {11, 15, 6, 8, 9, 10}; + int x1 = 16; + + int[] arr2 = {11, 15, 26, 38, 9, 10}; + int x2 = 35; + + int[] arr3 = {11, 15, 26, 38, 9, 10}; + int x3 = 45; + + System.out.println(isSumPair(arr1, x1)); + + } +} diff --git a/1_Arrays/Array17_MergeOperationToMakeArrayPalindrome.java b/1_Arrays/Array17_MergeOperationToMakeArrayPalindrome.java new file mode 100644 index 0000000..ed28e45 --- /dev/null +++ b/1_Arrays/Array17_MergeOperationToMakeArrayPalindrome.java @@ -0,0 +1,35 @@ + +public class Array17_MergeOperationToMakeArrayPalindrome { + + public static int mergeOperationNeed(int[] arr) { + int leftPoint = 0, rightPoint = arr.length-1; + int ans = 0; + + while(leftPoint <= rightPoint) { + if(arr[leftPoint] == arr[rightPoint]) { + leftPoint++; + rightPoint--; + } else if(arr[leftPoint] > arr[rightPoint]) { + rightPoint--; + arr[rightPoint] += arr[rightPoint+1]; + ans++; + } else { + leftPoint++; + arr[leftPoint] += arr[leftPoint-1]; + ans++; + } + } + + return ans; + } + + public static void main(String[] args) { + int[] arr1 = {15, 4, 15}; + int[] arr2 = {1, 4, 5, 1}; + int[] arr3 = {11, 14, 15, 99}; + int[] arr4 = {1, 4, 3, 3, 5, 1}; + int[] arr5 = {11, 14, 1, 1, 15, 99}; + + System.out.println(mergeOperationNeed(arr5)); + } +} diff --git a/1_Arrays/Array18_MoveZeros.java b/1_Arrays/Array18_MoveZeros.java new file mode 100644 index 0000000..110e7ec --- /dev/null +++ b/1_Arrays/Array18_MoveZeros.java @@ -0,0 +1,53 @@ +/* +Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. +Note that you must do this in-place without making a copy of the array. + +Example 1: +Input: nums = [0,1,0,3,12] +Output: [1,3,12,0,0] + +Example 2: +Input: nums = [0] +Output: [0] + +Constraints: + + 1 <= nums.length <= 104 + -231 <= nums[i] <= 231 - 1 + + */ + +public class Array18_MoveZeros { + + public static void moveZero(int[] arr) { //TC -> O(n) | SC ->O(1) + int zero = 0, i = 0; //tow pointers + + while(i < arr.length) { + if(arr[zero] == 0 && arr[i] != 0) { //if we found zero and non zero value swap them...... + //swap + arr[zero++] = arr[i]; + arr[i] = 0; + } else if(arr[zero] != 0) { //if current element is not zero....move to the next + zero++; + } + i++; + } + + printArray(arr); //print the array + } + + public static void printArray(int[] arr) { + for(int i = 0; i < arr.length; i++) { + System.out.print(arr[i]+" "); + } + } + + public static void main(String[] args) { + int[] arr1 = {0,1,0,3,12}; + int[] arr2 = {0}; + int[] arr3 = {0,0,0,1,4,5,0,0,0}; + int[] arr4 = {0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,0}; + + moveZero(arr4); + } +} diff --git a/1_Arrays/Array19_RunningSum.java b/1_Arrays/Array19_RunningSum.java new file mode 100644 index 0000000..bd0d91d --- /dev/null +++ b/1_Arrays/Array19_RunningSum.java @@ -0,0 +1,48 @@ +/* +Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). +Return the running sum of nums. + +Example 1: +Input: nums = [1,2,3,4] +Output: [1,3,6,10] +Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. + +Example 2: +Input: nums = [1,1,1,1,1] +Output: [1,2,3,4,5] +Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. + +Example 3: +Input: nums = [3,1,2,10,1] +Output: [3,4,6,16,17] + +Constraints: + + 1 <= nums.length <= 1000 + -10^6 <= nums[i] <= 10^6 + + */ + +public class Array19_RunningSum { + + public static void runningSumOFArray(int[] arr) { + for(int i = 1; i < arr.length; i++) { + arr[i] += arr[i-1]; + } + printArray(arr); + } + + public static void printArray(int[] arr) { + for( int i = 0; i < arr.length; i++) { + System.out.print(arr[i]+" "); + } + } + + public static void main(String[] args) { + int[] arr1 = {1,2,3,4}; + int[] arr2 = {1,1,1,1,1}; + int[] arr3 = {3,1,2,10,1}; + + runningSumOFArray(arr1); + } +} diff --git a/1_Arrays/Array20_FindPivotIndex.java b/1_Arrays/Array20_FindPivotIndex.java new file mode 100644 index 0000000..d0ebd11 --- /dev/null +++ b/1_Arrays/Array20_FindPivotIndex.java @@ -0,0 +1,63 @@ +/* +Given an array of integers nums, calculate the pivot index of this array. +The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. +If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. +Return the leftmost pivot index. If no such index exists, return -1. + +Example 1: +Input: nums = [1,7,3,6,5,6] +Output: 3 +Explanation: +The pivot index is 3. +Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 +Right sum = nums[4] + nums[5] = 5 + 6 = 11 + +Example 2: +Input: nums = [1,2,3] +Output: -1 +Explanation: +There is no index that satisfies the conditions in the problem statement. + +Example 3: +Input: nums = [2,1,-1] +Output: 0 +Explanation: +The pivot index is 0. +Left sum = 0 (no elements to the left of index 0) +Right sum = nums[1] + nums[2] = 1 + -1 = 0 + + +Constraints: + 1 <= nums.length <= 104 + -1000 <= nums[i] <= 1000 + */ + +public class Array20_FindPivotIndex { + + public static int pivotIndex(int[] arr) { + for(int i = 0; i < arr.length; i++) { + int leftSum = 0, rightSum = 0; + + for(int left = 0; left < i; left++) { + leftSum += arr[left]; + } + for(int right = i+1; right < arr.length; right++) { + rightSum += arr[right]; + } + + if(leftSum == rightSum) { + return i; + } + } + + return -1; + } + + public static void main(String[] args) { + int[] arr1 = {1,7,3,6,5,6}; + int[] arr2 = {1,2,3}; + int[] arr3 = {2,1,-1}; + + System.out.println("Pivot Point -> "+ pivotIndex(arr2)); + } +} diff --git a/1_Arrays/Array21_MajorityElement.java b/1_Arrays/Array21_MajorityElement.java new file mode 100644 index 0000000..f943cb5 --- /dev/null +++ b/1_Arrays/Array21_MajorityElement.java @@ -0,0 +1,57 @@ +/* +Given an array nums of size n, return the majority element. +The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. + +Example 1: +Input: nums = [3,2,3] +Output: 3 + +Example 2: +Input: nums = [2,2,1,1,1,2,2] +Output: 2 + +Constraints: + n == nums.length + 1 <= n <= 5 * 104 + -109 <= nums[i] <= 109 + +Follow-up: Could you solve the problem in linear time and in O(1) space? + */ + + +import java.util.Arrays; +public class Array21_MajorityElement { + + public static int bruteForce(int[] arr) { //TC -> O(n*log(n)) | SC -> O(1) + Arrays.sort(arr); + return arr[arr.length/2]; + } + + public static int majorityElement(int[] arr) { //TC -> O(n) | SC -> O(1) + int candidate = 0, vote = 0; + + for(int a : arr) { + if(vote == 0) { + candidate = a; + } + + if(candidate == a) { + vote++; + } else { + vote--; + } + } + return candidate; + } + + public static void main(String[] args) { + int[] arr1 = {3,2,3}; + int[] arr2 = {1,2,1,2,2,1,2}; + int[] arr3 = {2,2,2,2,1,1,1}; + int[] arr4 = {1,1,1,2,2,2,2}; + int[] arr5 = {1,2,2,2,2,1,1}; + int[] arr6 = {2,2,1,1,1,2,2}; + + System.out.println("Majority Element -> "+ majorityElement(arr4)); + } +} diff --git a/1_Arrays/Array22_FibonacciNumber.java b/1_Arrays/Array22_FibonacciNumber.java new file mode 100644 index 0000000..a62a2ae --- /dev/null +++ b/1_Arrays/Array22_FibonacciNumber.java @@ -0,0 +1,40 @@ +/* +The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, + +F(0) = 0, F(1) = 1 +F(n) = F(n - 1) + F(n - 2), for n > 1. +Given n, calculate F(n). + +Example 1: +Input: n = 2 +Output: 1 +Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. + +Example 2: +Input: n = 3 +Output: 2 +Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. + +Example 3: +Input: n = 4 +Output: 3 +Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. + +Constraints: + 0 <= n <= 30 + */ + +public class Array22_FibonacciNumber { + + public static int fibonacci(int number) { + if(number < 2) { + return number; + } + + return fibonacci(number-1) + fibonacci(number-2); + } + + public static void main(String[] args) { + System.out.println("Fibonacci >> "+ fibonacci(5)); + } +} diff --git a/1_Arrays/Array23_SquareOfSortedArray.java b/1_Arrays/Array23_SquareOfSortedArray.java new file mode 100644 index 0000000..aec63f8 --- /dev/null +++ b/1_Arrays/Array23_SquareOfSortedArray.java @@ -0,0 +1,54 @@ +/* +Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. + +Example 1: +Input: nums = [-4,-1,0,3,10] +Output: [0,1,9,16,100] +Explanation: After squaring, the array becomes [16,1,0,9,100]. +After sorting, it becomes [0,1,9,16,100]. + +Example 2: +Input: nums = [-7,-3,2,3,11] +Output: [4,9,9,49,121] + +Constraints: + 1 <= nums.length <= 104 + -104 <= nums[i] <= 104 + nums is sorted in non-decreasing order. + +Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach? + */ + + +public class Array23_SquareOfSortedArray { + public static void squareOfArray(int[] arr) { //TC -> O(n) | SC -> O(n) + int leftIndex = 0, rightIndex = arr.length-1; + int[] newArr = new int[arr.length]; + for(int i = arr.length-1; i >= 0; i--) { + if(Math.abs(arr[leftIndex]) >= Math.abs(arr[rightIndex])) { + newArr[i] = arr[leftIndex]*arr[leftIndex]; + leftIndex++; + } else { + newArr[i] = arr[rightIndex]*arr[rightIndex]; + rightIndex--; + } + } + + printArray(newArr); + } + + public static void printArray(int[] arr) { + for(int i = 0; i < arr.length; i++) { + System.out.print(arr[i]+" "); + } + System.out.println(); + } + + public static void main(String[] args) { + int[] arr1 = {-4,-1,0,3,10}; + int[] arr2 = {-7,-3,2,3,11}; + int[] arr3 = {-10,-6,-4,-3,-2}; + + squareOfArray(arr1); + } +} diff --git a/1_Arrays/Array24_PascalTriangle.java b/1_Arrays/Array24_PascalTriangle.java new file mode 100644 index 0000000..aa764b4 --- /dev/null +++ b/1_Arrays/Array24_PascalTriangle.java @@ -0,0 +1,46 @@ +/* +Given an integer numRows, return the first numRows of Pascal's triangle. +In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: + +Example 1: +Input: numRows = 5 +Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] + +Example 2: +Input: numRows = 1 +Output: [[1]] + +Constraints: + + 1 <= numRows <= 30 + + + */ + +import java.util.ArrayList; +public class Array24_PascalTriangle { + + public static void printPascalTriangle(int rowNum) { + ArrayList> list = new ArrayList<>(); + ArrayList listN = new ArrayList<>(); + + for(int i = 0; i < rowNum; i++) { + ArrayList inside = new ArrayList<>(); + for(int j = 0; j <= i; j++) { + if(j == 0 || j == i) { + inside.add(j, 1); + } else { + inside.add(j, listN.get(j)+listN.get(j-1)); + } + } + listN = inside; + list.add(i,listN); + } + + System.out.println(list); + } + + public static void main(String[] args) { + printPascalTriangle(5); + } +} diff --git a/1_Arrays/Array25_SpiralMatrix.java b/1_Arrays/Array25_SpiralMatrix.java new file mode 100644 index 0000000..e68e621 --- /dev/null +++ b/1_Arrays/Array25_SpiralMatrix.java @@ -0,0 +1,63 @@ +/* +Given an m x n matrix, return all elements of the matrix in spiral order. + +Example 1: +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [1,2,3,6,9,8,7,4,5] + +Example 2: +Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] +Output: [1,2,3,4,8,12,11,10,9,5,6,7] + +Constraints: + + m == matrix.length + n == matrix[i].length + 1 <= m, n <= 10 + -100 <= matrix[i][j] <= 100 + */ + + import java.util.ArrayList; +public class Array25_SpiralMatrix { + + public static void spiralPrint(int[][] arr) { + int startRow = 0, startColumn = 0, endRow = arr.length-1, endColumn = arr[0].length-1; + + while(startRow <= endRow && startColumn <= endColumn) { + //top boundary + for(int j = startColumn; j <= endColumn; j++) { + System.out.print(arr[startRow][j]+" "); + } + //right boundary + for(int i = startRow+1; i <= endRow; i++) { + System.out.print(arr[i][endColumn]+" "); + } + //bottom Boundary + for(int j = endColumn-1; j >= startColumn; j--) { + if(startRow == endRow) { + break; + } + System.out.print(arr[endRow][j]+" "); + } + //left boundary + for(int i = endRow-1; i >= startRow+1; i--) { + if(endColumn == endRow) { + break; + } + System.out.print(arr[i][startColumn]+" "); + } + + startRow++; + endRow--; + startColumn++; + endColumn--; + } + + } + + public static void main(String[] args) { + int[][] arr2 = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; + spiralPrint(arr2); + + } +} diff --git a/1_Arrays/Array26_RotateImage.java b/1_Arrays/Array26_RotateImage.java new file mode 100644 index 0000000..8ac4ad2 --- /dev/null +++ b/1_Arrays/Array26_RotateImage.java @@ -0,0 +1,55 @@ +/* +You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).s +You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. + + +Example 1: +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[7,4,1],[8,5,2],[9,6,3]] + +Example 2: +Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] +Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] + +Constraints: + + n == matrix.length == matrix[i].length + 1 <= n <= 20 + -1000 <= matrix[i][j] <= 1000 + + + */ + +public class Array26_RotateImage { + + public static void rotateImg(int[][] matrix) { + int n = matrix.length; + for(int i = 0; i < (n+1)/2 ; i++) { + for(int j = 0; j < n/2; j++) { + int temp = matrix[i][j]; + + matrix[i][j] = matrix[n-1-j][i]; + matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; + matrix[n-1-i][n-1-j] = matrix[j][n-1-i]; + matrix[j][n-1-i] = temp; + } + } + print2DArray(matrix); + } + + public static void print2DArray(int[][] arr) { + for(int i = 0; i < arr.length; i++) { + for(int j = 0; j < arr[0].length; j++) { + System.out.print(arr[i][j]+" "); + } + System.out.println(); + } + } + + + + public static void main(String[] args) { + int[][] arr = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; + rotateImg(arr); + } +} diff --git a/1_Arrays/Array27_DiagonalSum.java b/1_Arrays/Array27_DiagonalSum.java new file mode 100644 index 0000000..696333b --- /dev/null +++ b/1_Arrays/Array27_DiagonalSum.java @@ -0,0 +1,34 @@ + +public class Array27_DiagonalSum { + + public static int diagonalSum(int[][] arr) { + int n = arr.length; + int sum = 0; + /*for(int i = 0, j = 0; i < n; i++,j++) { + sum += arr[i][j]; + } + + for(int i = 0, j = n-1; i < n; i++,j--) { + sum += arr[i][j]; + } + + System.out.println(sum);*/ + for(int i = 0; i < n; i++) { + sum += arr[i][i]; + + if(i != n-1-i) { + sum += arr[i][n-1-i]; + } + } + + return sum; + } + + public static void main(String[] args) { + int[][] arr1 = {{1,2},{3,4}}; + int[][] arr2 = {{1,2,3},{4,5,6},{7,8,9}}; + int[][] arr3 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; + + System.out.println(diagonalSum(arr2)); + } +} diff --git a/1_Arrays/Array28_2Sum.java b/1_Arrays/Array28_2Sum.java new file mode 100644 index 0000000..bec2cb9 --- /dev/null +++ b/1_Arrays/Array28_2Sum.java @@ -0,0 +1,71 @@ +/* +Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. +You may assume that each input would have exactly one solution, and you may not use the same element twice. +You can return the answer in any order. + +Example 1: +Input: nums = [2,7,11,15], target = 9 +Output: [0,1] +Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. + +Example 2: +Input: nums = [3,2,4], target = 6 +Output: [1,2] + +Example 3: +Input: nums = [3,3], target = 6 +Output: [0,1] + + + +Constraints: + + 2 <= nums.length <= 104 + -109 <= nums[i] <= 109 + -109 <= target <= 109 + Only one valid answer exists. + + +Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? + */ + +import java.util.ArrayList; +import java.util.Arrays; +public class Array28_2Sum { + + public static void _2sum(int[] arr, int target) { //TC->O(n) + ArrayList list = new ArrayList<>(); + + Arrays.sort(arr); //Sort the array + + int start = 0, end = arr.length-1; //two pointers + + while(start < end) { + int sum = arr[start] + arr[end]; + if(sum == target) { + list.add(arr[start]); + list.add(arr[end]); + + System.out.println(list); + return; + } else if(sum > target) { + end--; + } else { + start++; + } + } + System.out.println(-1); + } + + public static void main(String[] args) { + int[] arr1 = {2,7,11,15,10,-1,-2,8,3};//(-2,-1,2,3,7,8,10,11,15) + int target1 = 11; + + int[] arr2 = {3,2,4}; + int target2 = 6; + + int[] arr3 = {}; + + _2sum(arr1, target1); + } +} diff --git a/1_Arrays/Array29_3Sum.java b/1_Arrays/Array29_3Sum.java new file mode 100644 index 0000000..186a2db --- /dev/null +++ b/1_Arrays/Array29_3Sum.java @@ -0,0 +1,77 @@ +/* +Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. +Notice that the solution set must not contain duplicate triplets. + +Example 1: +Input: nums = [-1,0,1,2,-1,-4] +Output: [[-1,-1,2],[-1,0,1]] +Explanation: +nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. +nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. +nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. +The distinct triplets are [-1,0,1] and [-1,-1,2]. +Notice that the order of the output and the order of the triplets does not matter. + +Example 2: +Input: nums = [0,1,1] +Output: [] +Explanation: The only possible triplet does not sum up to 0. + +Example 3: +Input: nums = [0,0,0] +Output: [[0,0,0]] +Explanation: The only possible triplet sums up to 0. + +Constraints: + 3 <= nums.length <= 3000 + -105 <= nums[i] <= 105 + */ + + +import java.util.ArrayList; +import java.util.Arrays; +public class Array29_3Sum { + + public static void _3Sum(int[] arr) { + ArrayList> list = new ArrayList<>(); + ArrayList num = new ArrayList<>(); + int n = arr.length; + + Arrays.sort(arr); //sorting the array + + for(int i = 0; i < n-1; i++) { + int start = i+1, end = n-1; + + while(start < end) { + int sum = arr[i]+arr[start]+arr[end]; + + if(sum == 0) { + num.add(0, arr[i]); + num.add(1, arr[start]); + num.add(2, arr[end]); + start++; + end--; + } else if(sum > 0) { + end--; + } else { + start++; + } + + list.add(num); + } + } + + System.out.println(list); + + } + + public static void main(String[] args) { + int[] arr1 = {-1,0,1,2,-1,-4}; //[-4,-1,-1,0,1,2] + int[] arr2 = {0,1,1}; + int[] arr3 = {0,0,0}; + int[] arr = {}; + + _3Sum(arr1); + + } +} diff --git a/1_Arrays/Array31_SubArraySumEqualsK.java b/1_Arrays/Array31_SubArraySumEqualsK.java new file mode 100644 index 0000000..303b052 --- /dev/null +++ b/1_Arrays/Array31_SubArraySumEqualsK.java @@ -0,0 +1,44 @@ +/* +Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. +A subarray is a contiguous non-empty sequence of elements within an array. + +Example 1: +Input: nums = [1,1,1], k = 2 +Output: 2 + +Example 2: +Input: nums = [1,2,3], k = 3 +Output: 2 + +Constraints: + 1 <= nums.length <= 2 * 104 + -1000 <= nums[i] <= 1000 + -107 <= k <= 107 + */ + +public class Array31_SubArraySumEqualsK { + + public static int subArrayNumber(int[] arr, int k) { //TC -> O(n^2) || O(1) + int count = 0; + + for(int i = 0; i < arr.length; i++) { + if(arr[i] == k) count++; + int j = i+1; + int sum = arr[i]; + while(i < j) { + sum += arr[j]; + if(sum == k) count++; + j--; + } + } + + return count; + } + + public static void main(String[] args) { + int[] arr1 = {1,1,1}; + int[] arr2 = {1,2,3}; + + System.out.println(subArrayNumber(arr1, 1)); + } +} \ No newline at end of file diff --git a/1_Arrays/Array33_4Sum.java b/1_Arrays/Array33_4Sum.java new file mode 100644 index 0000000..c5ee204 --- /dev/null +++ b/1_Arrays/Array33_4Sum.java @@ -0,0 +1,71 @@ +/* +Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: +0 <= a, b, c, d < n +a, b, c, and d are distinct. +nums[a] + nums[b] + nums[c] + nums[d] == target +You may return the answer in any order. + +Example 1: +Input: nums = [1,0,-1,0,-2,2], target = 0 +Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] + +Example 2: +Input: nums = [2,2,2,2,2], target = 8 +Output: [[2,2,2,2]] + +Constraints: +1 <= nums.length <= 200 +-109 <= nums[i] <= 109 +-109 <= target <= 109 +*/ + +import java.util.ArrayList; +import java.util.List; +import java.util.Arrays; +public class Array33_4Sum { + + public static void _4Sum(int[] arr, int target) { + List> output = new ArrayList<>(); + int n = arr.length; //size of array + + Arrays.sort(arr); //sort the array + + for(int i = 0; i < n; i++) { + for(int j = i+1; j < n; j++) { + int start = j+1, end = n-1; + + while(start < end) { + int sum = arr[i]+arr[j]+arr[start]+arr[end]; + + if(sum == target) { + output.add(Arrays.asList(arr[i],arr[j],arr[start],arr[end])); + start++; + end--; + + while(start < end && arr[start] == arr[start+1]) start++; + while(start < end && arr[end] == arr[end-1]) end--; + } else if(sum > target) { + end--; + } else { + start++; + } + + } + while(j+1 < n && arr[j] == arr[j+1]) j++; + } + while(i+1 < n && arr[i] == arr[i+1]) i++; + } + + System.out.println(output); + } + + public static void main(String[] args) { + int[]arr1 = {1,0,-1,0,-2,2}; + int target1 = 0; + + int[] arr2 = {2,2,2,2,2}; + int target2 = 8; + + _4Sum(arr1, target1); + } +}