LC 150 (first part) Flashcards
(41 cards)
- Merge Sorted Array
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
public void merge(int[] nums1, int m, int[] nums2, int n) { int writer = nums1.length - 1; int reader1 = m - 1; int reader2 = n - 1; while (writer >= 0 && reader1 >= 0 && reader2 >= 0) { if (nums1[reader1] > nums2[reader2]) { nums1[writer] = nums1[reader1]; reader1--; } else { nums1[writer] = nums2[reader2]; reader2--; } writer--; } // If there are remaining elements in nums2, copy them to nums1 while (reader2 >= 0) { nums1[writer] = nums2[reader2]; writer--; reader2--; } }
- Remove Element
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
public int removeElement(int[] nums, int val) { int j = 0; for(int i = 0; i< nums.length; i++){ if(nums[i] != val){ nums[j] = nums[i]; j++; } } return j; }
- Remove Duplicates from Sorted Array
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).
class Solution { public int removeDuplicates(int[] nums) { int j = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[i - 1]) { nums[j] = nums[i]; j++; } } return j; } }
- Majority Element
Input: nums = [3,2,3]
Output: 3
class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; } }
- Rotate Array
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
class Solution { public void rotate(int[] nums, int k) { k %= nums.length; reverse(nums, 0, nums.length - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.length - 1); } public void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } }
- Best Time to Buy and Sell Stock
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.
class Solution { public int maxProfit(int[] prices) { int lowestPrice = Integer.MAX_VALUE; int maxProfit = 0; for(int i = 0; i < prices.length; i++){ } } }
- Best Time to Buy and Sell Stock II
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
class Solution { public int maxProfit(int[] prices) { int maxprofit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) maxprofit += prices[i] - prices[i - 1]; } return maxprofit; } }
- Jump Game
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
public class Solution { public boolean canJump(int[] nums) { int lastPos = nums.length - 1; for (int i = nums.length - 1; i >= 0; i--) { if (i + nums[i] >= lastPos) { lastPos = i; } } return lastPos == 0; } }
- Jump Game II
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
class Solution { public int jump(int[] nums) { // The starting range of the first jump is [0, 0] int answer = 0, n = nums.length; int curEnd = 0, curFar = 0; for (int i = 0; i < n - 1; ++i) { // Update the farthest reachable index of this jump. curFar = Math.max(curFar, i + nums[i]); // If we finish the starting range of this jump, // Move on to the starting range of the next jump. if (i == curEnd) { answer++; curEnd = curFar; } } return answer; } }
- Product of Array Except Self
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
class Solution { public int[] productExceptSelf(int[] nums) { int length = nums.length; int[] L = new int[length]; int[] R = new int[length]; int[] answer = new int[length]; L[0] = 1; for (int i = 1; i < length; i++) { L[i] = nums[i - 1] * L[i - 1]; } R[length - 1] = 1; for (int i = length - 2; i >= 0; i--) { R[i] = nums[i + 1] * R[i + 1]; } for (int i = 0; i < length; i++) { answer[i] = L[i] * R[i]; } return answer; } }
- Length of Last Word
Input: s = “Hello World”
Output: 5
Explanation: The last word is “World” with length 5.
class Solution { public int lengthOfLastWord(String s) { s = s.trim(); // trim the trailing spaces in the string return s.length() - s.lastIndexOf(" ") - 1; } }
- Longest Common Prefix
Input: strs = [“flower”,”flow”,”flight”]
Output: “fl”
class Solution { public String longestCommonPrefix(String[] strs) { StringBuilder result = new StringBuilder(); for(int i = 0; i < strs[0].length(); i++) { char c = strs[0].charAt(i); for (int j = 1; j< strs.length; j++) { if(i > strs[j].length()-1){ return result.toString(); } char b = strs[j].charAt(i); if(b!=c){ return result.toString(); } } result.append(c); } return result.toString(); } }
- Reverse Words in a String
Input: s = “the sky is blue”
Output: “blue is sky the”
class Solution { public String reverseWords(String s) { String[] split = s.trim().split(" "); int left = 0; int right = split.length - 1; while( left < right ) { String temp = split[left]; split[left] = split[right]; split[right] = temp; left++; right--; } StringBuffer result = new StringBuffer(); for(String s1: split) { if(s1!=""){ result.append(s1); result.append(" "); } } return result.toString().trim(); } }
- Zigzag Conversion
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
class Solution { public String convert(String s, int numRows) { if (numRows == 1) { return s; } StringBuilder answer = new StringBuilder(); int n = s.length(); int charsInSection = 2 * (numRows - 1); for (int currRow = 0; currRow < numRows; ++currRow) { int index = currRow; while (index < n) { answer.append(s.charAt(index)); // If currRow is not the first or last row // then we have to add one more character of current section. if (currRow != 0 && currRow != numRows - 1) { int charsInBetween = charsInSection - 2 * currRow; int secondIndex = index + charsInBetween; if (secondIndex < n) { answer.append(s.charAt(secondIndex)); } } // Jump to same row's first character of next section. index += charsInSection; } } return answer.toString(); } }
- Find the Index of the First Occurrence in a String
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.
class Solution { public int strStr(String haystack, String needle) { int m = needle.length(); int n = haystack.length(); for (int windowStart = 0; windowStart <= n - m; windowStart++) { for (int i = 0; i < m; i++) { if (needle.charAt(i) != haystack.charAt(windowStart + i)) { break; } if (i == m - 1) { return windowStart; } } } return -1; } }
- Valid Palindrome
Input: s = “A man, a plan, a canal: Panama”
Output: true
Explanation: “amanaplanacanalpanama” is a palindrome.
class Solution { public boolean isPalindrome(String s) { for( int i = 0, j = s.length() - 1; i < j; i++, j-- ) { while (i < j && !Character.isLetterOrDigit(s.charAt(i))) { i++; } // Skip non-alphanumeric characters from the end while (i < j && !Character.isLetterOrDigit(s.charAt(j))) { j--; } if(Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))){ return false; } } return true; } }
- Is Subsequence
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., “ace” is a subsequence of “abcde” while “aec” is not).
Input: s = “abc”, t = “ahbgdc”
Output: true
Input: s = “axc”, t = “ahbgdc”
Output: false
class Solution { public boolean isSubsequence(String s, String t) { int sPointer = 0; int tPointer = 0; if(s.equals("")) return true; while(sPointer < s.length() &&tPointer < t.length()) { if(s.charAt(sPointer) == t.charAt(tPointer)){ sPointer++; tPointer++; if(sPointer >= s.length()) return true; } else { tPointer++; } } return false; } }
- Two Sum II - Input Array Is Sorted
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
class Solution { public int[] twoSum(int[] numbers, int target) { int lo = 0, hi = numbers.length - 1; while (lo < hi) { int curSum = numbers[lo] + numbers[hi]; if (curSum == target) { return new int[]{lo + 1, hi + 1}; } else if (curSum > target) { hi--; } else { lo++; } } return new int[]{-1, -1}; } }
- Container With Most Water
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.
class Solution { public int maxArea(int[] height) { int max = 0; int l = 0; int r = height.length - 1; while(l<r){ int h = Math.min(height[l], height[r]); int w = r-l; max = Math.max(max, h * w); if(height[l] < height[r]){ l++; } else { r--; } } return max; } }
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Input: ransomNote = “a”, magazine = “b”
Output: false
Input: ransomNote = “aa”, magazine = “ab”
Output: false
class Solution { public boolean canConstruct(String ransomNote, String magazine) { HashMap<Character,Integer> magazineMap = new HashMap<>(); for(Character c: magazine.toCharArray()){ magazineMap.put(c, magazineMap.getOrDefault(c,0) +1); } for(Character c: ransomNote.toCharArray()){ if(magazineMap.containsKey(c)){ int count = magazineMap.get(c); if(count < 1){ return false; } else { magazineMap.put(c, count - 1); } } else { return false; } } return true; } }
- Isomorphic Strings
Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Example 1:
Input: s = “egg”, t = “add”
Output: true
Example 2:
Input: s = “foo”, t = “bar”
Output: false
class Solution { public boolean isIsomorphic(String s, String t) { if(s.length() != t.length()) return false; HashMap<Character,Character> map = new HashMap<Character,Character>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(map.containsKey(c) ){ if(map.containsKey(c)){ char mapped = map.get(c); if(mapped != t.charAt(i)) { return false; } } } else { if(map.containsValue(t.charAt(i))) return false; map.put(c, t.charAt(i)); } } return true; } }
- Word Pattern
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Example 1:
Input: pattern = “abba”, s = “dog cat cat dog”
Output: true
Example 2:
Input: pattern = “abba”, s = “dog cat cat fish”
Output: false
Example 3:
Input: pattern = “aaaa”, s = “dog cat cat dog”
Output: false
class Solution { public boolean wordPattern(String pattern, String s) { String[] splitted = s.split(" "); if(pattern.length() != splitted.length) return false; HashMap<Character, String> map = new HashMap<>(); HashMap<String, Character> reverseMap = new HashMap<>(); for(int i = 0; i < pattern.length(); i++) { Character c = pattern.charAt(i); if(map.containsKey(c)){ String val = map.get(c); if(!val.equals(splitted[i])) return false; } else if (reverseMap.containsKey(splitted[i])) { return false; } else { map.put(c, splitted[i]); reverseMap.put(splitted[i], c); } } return true; } }
- Valid Anagram
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: false
class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()){ return false; } return sort(s).equals(sort(t)); } public String sort(String s) { char[] cArr = s.toCharArray(); java.util.Arrays.sort(cArr); return new String(cArr); } }
- Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
Example 2:
Input: strs = [””]
Output: [[””]]
Example 3:
Input: strs = [“a”]
Output: [[“a”]]
import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; class Solution { public List<List<String>> groupAnagrams(String[] strs) { HashMap<String, List> map = new HashMap<String, List>(); for(String s: strs) { String key = sort(s); if(map.containsKey(key)) { map.get(key).add(s); } else { LinkedList<String> list = new LinkedList<>(); list.add(s); map.put(key, list); } } List<List<String>> result = new LinkedList<List<String>>(); //for(Entry<String, List> e: map.entrySet()) { // result.add(e.getValue());//returns list //} result.addAll(map.values()); return result; } public String sort(String s) { char[] cArr = s.toCharArray(); java.util.Arrays.sort(cArr); return new String(cArr); } }