combined

¡Supera tus tareas y exámenes ahora con Quizwiz!

645. Set Mismatch You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array.

public int[] findErrorNums(int[] nums) { int N = nums.length, sum = N * (N + 1) / 2; int[] ans = new int[2]; boolean[] seen = new boolean[N+1]; for (int num : nums) { sum -= num; if (seen[num]) ans[0] = num; seen[num] = true; } ans[1] = sum + ans[0]; return ans; }

first letter to lowercase

String input = "SomeInputString"; String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : ""); String input = "SomeInputString"; char c[] = input.toCharArray(); c[0] = Character.toLowerCase(c[0]); String output = new String(c); StringBuilder sb = new StringBuilder(string); sb.setCharAt(0, Character.toLowerCase(sb.charAt(0))); string = sb.toString(); char c[] = string.toCharArray(); c[0] = Character.toLowerCase(c[0]);

693. Binary Number with Alternating Bits Easy 1.2K 109 Companies Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

class Solution { public boolean hasAlternatingBits(int n) { String l = Integer.toBinaryString(n); for(int i = 0 ; i< l.length() -1 ; i++){ if(l.charAt(i) == l.charAt(i+1)) return false; } return true; } }

2135. Count Words Obtained After Adding a Letter

https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/description/

2325. Decode the Message

https://leetcode.com/problems/decode-the-message/description/

762. Prime Number of Set Bits in Binary Representation Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. For example, 21 written in binary is 10101, which has 3 set bits.

public int countPrimeSetBits(int left, int right) { int cnt=0; for(int i=left;i<=right;i++) if(isPrime(Integer.bitCount(i))) cnt++; return cnt; } public static boolean isPrime(int num) { if(num<=1) return false; for(int i=2;(i*i)<=num;i++) if((num%i)==0) return false; return true; }

2595. Number of Even and Odd Bits Easy 184 68 Companies You are given a positive integer n. Let even denote the number of even indices in the binary representation of n (0-indexed) with value 1. Let odd denote the number of odd indices in the binary representation of n (0-indexed) with value 1. Return an integer array answer where answer = [even, odd].

public int[] evenOddBit(int n) { int even = 0; int odd = 0; for (int i=0; n > 0; i++, n /= 2) { if (i % 2 == 0) even += (n & 1); else odd += (n & 1); } return new int[] {even, odd}; }

338. Counting Bits Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

public int[] countBits(int n) { int[] ans = new int[n+1]; for(int i=0; i<=n; i++){ ans[i] = Integer.bitCount(i); } return ans; }

1324. Print Words Vertically Medium 682 109 Companies Given a string s. Return all the words vertically in the same order in which they appear in s.Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).Each word would be put on only one column and that in one column there will be only one word.

public List<String> printVertically(String s) { List<String> list = new ArrayList<>(); String[] arr = s.split(" "); int max = 0; for (String s1 : arr){ max = Math.max(max, s1.length()); } for (int i = 0; i < max; i++){ StringBuilder str = new StringBuilder(); int index = 0; for (int j = 0; j < arr.length; j++){ if (i >= arr[j].length()) { str.append(" "); } else { str.append(arr[j].charAt(i)); index = j + 1; } } list.add(str.substring(0, index)); } return list; }

2273. Find Resultant Array After Removing Anagrams Easy You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions. Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc".

public List<String> removeAnagrams(String[] words) { List<String> result = new LinkedList<>(); String lastAnagramStr = null; for (String s : words) { char[] charArr = s.toCharArray(); Arrays.sort(charArr); String curAnagramStr = new String(charArr); if (curAnagramStr.equals(lastAnagramStr)) { continue; } else { lastAnagramStr = curAnagramStr; result.add(s); } } return result; }

1451. Rearrange Words in a Sentence Given a sentence text (A sentence is a string of space-separated words) in the following format: First letter is in upper case. Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above.

public String arrangeWords(String text) { String text1 = Character.toLowerCase(text.charAt(0)) + (text.length() > 1 ? text.substring(1) : ""); String[] str = text1.split(" "); int [][] count = new int[str.length][2]; for(int i=0; i<str.length; i++){ count[i][0]=str[i].length(); count[i][1]=i; } Arrays.sort(count, (a,b)->Integer.compare(a[0],b[0])); StringBuffer sb = new StringBuffer(); for(int i=0; i<str.length; i++){ //if(i==0) str.chatAt[count[i][1] sb.append(str[count[i][1]]); if(i<str.length-1) sb.append(" "); } sb.setCharAt(0,Character.toUpperCase(sb.charAt(0))); return sb.toString(); }

524. Longest Word in Dictionary through Deleting Medium 1.7K 352 Companies Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

public String findLongestWord(String S, List<String> D) { String ans = ""; for (String word : D) { int a = word.length(), b = ans.length(); if (a < b || (a == b && word.compareTo(ans) > 0)) continue; int pos = -1; for (int i = 0; i < a; i++) { pos = S.indexOf(word.charAt(i), pos + 1); if (pos == -1) break; } if (pos != -1) ans = word; } return ans; }

179. Largest Number Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer.

public String largestNumber(int[] nums) { String[] s = new String[nums.length]; for(int i=0; i<nums.length; i++) s[i] = String.valueOf(nums[i]); Arrays.sort(s, (a,b) -> (b + a).compareTo(a + b)); return s[0].equals("0") ? "0" : String.join("",s); }

1903. Largest Odd Number in String Easy 934 67 Companies You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string.

public String largestOddNumber(String num) { for(int i=num.length()-1;i>=0;i--){ int n = num.charAt(i); if(n%2!=0) return num.substring(0,i+1); } return ""; }

2284. Sender With Largest Word Count Medium 350 31 Companies You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i]. A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message. Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.

public String largestWordCount(String[] messages, String[] senders) { Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < messages.length; i++) { int words = messages[i].split(" ").length; String name = senders[i]; map.put(name, words + map.getOrDefault(name, 0)); } String ans = ""; int max = 0; for (String name : map.keySet()) { int words = map.get(name); if (words > max) { max = words; ans = name; } else if (words == max) { int x = ans.compareTo(name); ans = (x > 0)? ans : name; } } return ans; }

720. Longest Word in Dictionary Medium 1.8K 1.4K Companies Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

public String longestWord(String[] words) { Arrays.sort(words); String ans = ""; HashSet<String> set= new HashSet<>(); for(String i: words) { if(i.length()==1 || set.contains(i.substring(0, i.length()-1))) { if(i.length()> ans.length()) { ans= i;} set.add(i); }} return ans; } }

557. Reverse Words in a String III Easy 4.9K 228 Companies Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

public String reverseWords(String s) { String x = ""; for(String t : s.split(" ")) x += new StringBuilder(t).reverse().toString()+" "; return x.trim(); }

1859. Sorting the Sentence Easy A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3".

public String sortSentence(String s) { String[] arr1= s.split("\\s"); String arr[]=new String[arr1.length]; for(int i=0; i<arr1.length; i++){ int j=arr1[i].charAt(arr1[i].length()-1)-'0'; arr[j-1]=arr1[i].substring(0,arr1[i].length()-1); } StringBuilder s1= new StringBuilder(); for(int i=0; i<arr.length; i++){ s1.append(arr[i]+ " "); } return s1.toString().trim(); }

405. Convert a Number to Hexadecimal Easy 1.2K 198 Companies Given an integer num, return a string representing its hexadecimal representation. For negative integers, two's complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

public String toHex(int num) { String hexValue = Integer.toHexString(num); return hexValue; }

405. Convert a Number to Hexadecimal Easy 1.2K 198 Companies Given an integer num, return a string representing its hexadecimal representation. For negative integers, two's complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem.

public String toHex(int num) { if(num<10 && num>=0) return Integer.toString(num); char[] hex = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; StringBuilder sb = new StringBuilder(); for(int i=0;i<8 && num!=0;i++) { sb.insert(0,hex[num & 15]); num = num>>4; } return sb.toString(); }

2418. Sort the People Easy You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. For each index i, names[i] and heights[i] denote the name and height of the ith person. Return names sorted in descending order by the people's heights.

public String[] sortPeople(String[] names, int[] heights) { //Space: O(N) //form a 2D array using people's height and their position in original array. int[][] people = new int[names.length][2]; for (int i = 0; i < names.length; i++) people[i] = new int[] {heights[i], i}; //Time: O(NlgN); Space: O(lgN) //sort in descending order by the people's heights. Arrays.sort(people, (a, b) -> b[0] - a[0]); String[] res = new String[names.length]; //Time: O(N) //Get result from sorted array. for (int i = 0; i < names.length; i++) res[i] = names[people[i][1]]; return res;

1662. Check If Two String Arrays are Equivalent Easy 2.2K 174 Companies Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string.

public boolean arrayStringsAreEqual(String[] word1, String[] word2) { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for(String s1: word1){sb1.append(s1);} for(String s2: word2){sb2.append(s2);} return sb1.toString().equals(sb2.toString()); } check another code with 4 pointers

2206. Divide Array Into Equal Pairs You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Each element belongs to exactly one pair. The elements present in a pair are equal. Return true if nums can be divided into n pairs, otherwise return false.

public boolean divideArray(int[] nums) { Arrays.sort(nums); for(int i = 0 ;i < nums.length ; i = i + 2){ if((nums[i] ^ nums[i + 1]) != 0){ return false; } } return true; }

2546. Apply Bitwise Operations to Make Strings Equal Medium 208 93 Companies You are given two 0-indexed binary strings s and target of the same length n. You can do the following operation on s any number of times: Choose two different indices i and j where 0 <= i, j < n. Simultaneously, replace s[i] with (s[i] OR s[j]) and s[j] with (s[i] XOR s[j]).

public boolean makeStringsEqual(String s, String t) { return s.contains("1") == t.contains("1");

459. Repeated Substring Pattern Easy 4.5K 397 Companies Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

public boolean repeatedSubstringPattern(String str) { int l = str.length(); for(int i=l/2;i>=1;i--) { if(l%i==0) { int m = l/i; String subS = str.substring(0,i); StringBuilder sb = new StringBuilder(); for(int j=0;j<m;j++) { sb.append(subS); } if(sb.toString().equals(str)) return true; } } return false; }

389. Find the Difference Easy You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t.

public char findTheDifference(String s, String t) { int randomLetter=0; for(char c:s.toCharArray()) randomLetter-=c; for(char c:t.toCharArray()) randomLetter+=c; return (char) randomLetter; }

1009. Complement of Base 10 Integer Easy 2.1K 104 Companies The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer n, return its complement.

public int bitwiseComplement(int n) { int mask = 1; while (mask < n) { mask = (mask << 1) | 1; } return ~n & mask; }

1773. Count Items Matching a Rule You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue. The ith item is said to match the rule if one of the following is true: ruleKey == "type" and ruleValue == typei. ruleKey == "color" and ruleValue == colori. ruleKey == "name" and ruleValue == namei. Return the number of items that match the given rule.

public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) { int res = 0; //for (List<String> item : items){ for(int i = 0 ;i<items.size();i++){ if(ruleKey.equals("type") && items.get(i).get(0).equals(ruleValue)) res++; if(ruleKey.equals("color") && items.get(i).get(1).equals(ruleValue)) res++; if(ruleKey.equals("name") && items.get(i).get(2).equals(ruleValue)) res++; } return res; }

2580. Count Ways to Group Overlapping Ranges Medium 251 15 Companies You are given a 2D integer array ranges where ranges[i] = [starti, endi] denotes that all integers between starti and endi (both inclusive) are contained in the ith range. You are to split ranges into two (possibly empty) groups such that: Each range belongs to exactly one group. Any two overlapping ranges must belong to the same group. Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges. For example, [1, 3] and [2, 5] are overlapping because 2 and 3 occur in both ranges.

public int countWays(int[][] ranges) { int res = 1, last = -1, mod = (int)1e9 + 7; Arrays.sort(ranges, (a, b) -> a[0] - b[0]); for (int[] r: ranges) { if (last < r[0]) res = res * 2 % mod; last = Math.max(last, r[1]); } return res;

522. Longest Uncommon Subsequence II Medium 459 1.2K Companies Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).

public int findLUSlength(String[] strs) { int n=strs.length; Arrays.sort(strs,(a,b)->b.length()-a.length()); for(int i=0;i<n;i++) { int flag=-1; for(int j=0;j<n;j++) { if(strs[j].length()<strs[i].length()) break; if(j==i) continue; if(!isPossible(strs[j],strs[i])) { flag++; break; } } if(flag==-1) return strs[i].length(); } return -1; } public boolean isPossible(String a, String b) { int n=a.length(); int m=b.length(); if(n==m && a.equals(b)) return false; int i=0,j=0; while(i<n && j<m) { if(a.charAt(i)==b.charAt(j)) j++; i++; } return j!=m; }

1371. Find the Longest Substring Containing Vowels in Even Counts Medium 1.5K 54 Companies Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.

public int findTheLongestSubstring(String s) { int res = 0 , mask = 0, n = s.length(); HashMap<Integer, Integer> seen = new HashMap<>();// key--> Mask, value--> Index seen.put(0, -1); for (int i = 0; i < n; ++i) { if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u'){ // check only vowels and skip consonant int c=s.charAt(i); mask=mask ^ c; seen.putIfAbsent(mask, i); } res = Math.max(res, i - seen.get(mask)); } return res; }

2740. Find the Value of the Partition You are given a positive integer array nums. Partition nums into two arrays, nums1 and nums2, such that: Each element of the array nums belongs to either the array nums1 or the array nums2. Both arrays are non-empty. The value of the partition is minimized. The value of the partition is |max(nums1) - min(nums2)|. Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the minimum element of the array nums2. Return the integer denoting the value of such partition.

public int findValueOfPartition(int[] nums) { Arrays.sort(nums); int diff = Integer.MAX_VALUE; for (int i = 0; i < nums.length - 1; i++) { diff = Math.min(diff, Math.abs(nums[i] - nums[i + 1])); } return diff; }

461. Hamming Distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them.

public int hammingDistance(int x, int y) { return Integer.bitCount(x^y);

1679. Max Number of K-Sum Pairs Medium 2.3K 51 Companies You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array.

public int maxOperations(int[] nums, int k) { HashMap<Integer,Integer>map=new HashMap<>(); int count=0; for(int i=0;i<nums.length;i++){ //to check if that k-nums[i] present and had some value left or already paired if(map.containsKey(k-nums[i])&&map.get(k-nums[i])>0){ count++; map.put(k-nums[i],map.get(k-nums[i])-1); }else{ //getOrDefault is easy way it directly checks if value is 0 returns 0 where I added 1 //and if some value is present then it return that value "similar to map.get(i)" and I added 1 on it map.put(nums[i],map.getOrDefault(nums[i],0)+1); } } return count; }

318. Maximum Product of Word Lengths Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.

public int maxProduct(String[] words) { int n = words.length; int[] masks = new int[n]; for (int i=0; i<n; i++) for (char c: words[i].toCharArray()) masks[i] |= (1 << (c - 'a')); int largest = 0; for (int i=0; i<n-1; i++) for (int j=i+1; j<n; j++) if ((masks[i] & masks[j]) == 0) largest = Math.max(largest, words[i].length() * words[j].length()); return largest;

1456. Maximum Number of Vowels in a Substring of Given Length Medium 2.7K 96 Companies Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

public int maxVowels(String s, int k) { int vowel = 0, count = 0; for(int i = 0; i < k; i++){ char c = s.charAt(i); if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++; } if(count > vowel) vowel = count; for(int i = k, j = 0; i < s.length(); i++,j++){ char c = s.charAt(i); char ch = s.charAt(j); if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++; if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') count--; if(count >= k) return k; if(count > vowel) vowel = count; } return vowel;

1684. Count the Number of Consistent Strings You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words.

public int maximumTastiness(int[] price, int k) { Arrays.sort(price); int low = 0, high = Integer.MAX_VALUE, mid; while (low <= high) { mid = (low + high) / 2; if (isPossible(price, k, mid)) { low = mid + 1; } else { high = mid - 1; } } return high; } boolean isPossible(int[] price, int k, int x) { int last = price[0], count = 1, i = 1; while ( i < price.length) { if (price[i] - last >= x) { last = price[i]; count++; } i++; if(count>=k) { return true; } } return count >= k; }

2517. Maximum Tastiness of Candy Basket Medium 642 73 Companies You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k. The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket. Return the maximum tastiness of a candy basket.

public int maximumTastiness(int[] price, int k) { Arrays.sort(price); int low = 1; int high = price[price.length-1]-price[0]; int ans = 0; while(low<=high) { int mid = low + (high-low)/2; int mark = price[0]; int count = 1; for(int i=1;i<price.length;i++) { if(price[i]>=mark+mid) { mark = price[i]; count++; } } if(count>=k) { ans = mid; low = mid+1; } else { high = mid-1; } } return ans; }

2220. Minimum Bit Flips to Convert Number A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc. Given two integers start and goal, return the minimum number of bit flips to convert start to goal.

public int minBitFlips(int start, int goal) { int count = 0; while(start!=0 || goal!=0){ if((start&1)!= (goal&1)){ count++; } start = start>>1; goal = goal>>1; } return count; }

2037. Minimum Number of Moves to Seat Everyone There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student. You may perform the following move any number of times: Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1) Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat. Note that there may be multiple seats or students in the same position at the beginning.

public int minMovesToSeat(int[] seats, int[] students) { int ans = 0; Arrays.sort(seats); Arrays.sort(students); for(int i=0; i<seats.length; i++){ ans+=Math.abs(seats[i]-students[i]); } return ans; }

268. Missing Number Easy Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

public int missingNumber(int[] nums) { int res = 0; for (int i = 0; i < nums.length; i++) { res += ((i + 1) - nums[i]); } return res; }

2114. Maximum Number of Words Found in Sentences Easy A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence.

public int mostWordsFound(String[] sentences) { int ans = 0; for(String sentence: sentences){ ans = Math.max(ans, sentence.split(" ").length); } return ans; }

825. Friends Of Appropriate Ages Medium 644 1.1K Companies There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0.5 * age[x] + 7 age[y] > age[x] age[y] > 100 && age[x] < 100 Otherwise, x will send a friend request to y.

public int numFriendRequests(int[] ages) { int n = ages.length, sum = 0; Arrays.sort(ages); for(int i = 0; i < n; i++){ for(int j = i-1; j >= 0; j--){ if(ages[i] >= 2 * (ages[j] - 7)) break; else sum++; } int k = i; while(k < n-1 && ages[++k] == ages[i]) if(ages[i]< 2 * (ages[k]-7)) sum++; } return sum; }

1498. Number of Subsequences That Satisfy the Given Sum Condition Medium 3.5K 302 Companies You are given an array of integers nums and an integer target. Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.

public int numSubseq(int[] nums, int target) { Arrays.sort(nums); int left = 0, right = nums.length - 1; long count = 0; int mod = 1_000_000_007; long[] power = new long[nums.length]; power[0] = 1; for (int i = 1; i < nums.length; i++) { power[i] = (power[i - 1] << 1) % mod; } while (left <= right) { if (nums[left] + nums[right] <= target) { count = (count + power[right - left]) % mod; left++; } else { right--; } } return (int) count; }

1887. Reduction Operations to Make the Array Elements Equal Medium 474 20 Companies Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest. Reduce nums[i] to nextLargest. Return the number of operations to make all elements in nums equal.

public int reductionOperations(int[] nums) { int count = 0, ans = 0; Arrays.sort(nums); for(int i=nums.length-1;i>=0;i--){ if(nums[i]==nums[0]) break; if(nums[i]>nums[i-1]){ count++; ans += count; }else if(nums[i]==nums[i-1]) count++; } return ans; }

1288. Remove Covered Intervals Medium 2.1K 56 Companies Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d. Return the number of remaining intervals.

public int removeCoveredIntervals(int[][] intervals) { ArrayList<ArrayList<Integer>>a1=new ArrayList<>(); Arrays.sort(intervals,(a,b)->a[0]==b[0]?b[1]-a[1]:a[0]-b[0]); for(int interval[]:intervals){ if(a1.size()==0||a1.get(a1.size()-1).get(1)<interval[1]){ ArrayList<Integer>s=new ArrayList<>(); s.add(interval[0]); s.add(interval[1]); a1.add(s); } } return a1.size(); }

1863. Sum of All Subset XOR Totals Easy The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty. For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1. Given an array nums, return the sum of all XOR totals for every subset of nums. Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.

public int subsetXORSum(int[] nums) { int total = 0; for (int i = 0; i < (1 << nums.length); i++) { int xor = 0; for (int j = 0; j < nums.length; j++) { if ((i & (1 << j)) != 0) { xor ^= nums[j]; } } total += xor; } return total; }

436. Find Right Interval Medium 1.8K 296 Companies You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j. Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.

public int[] findRightInterval(int[][] intervals) { TreeMap<Integer, Integer> map = new TreeMap<>(); for(int i = 0; i < intervals.length; i++){ map.put(intervals[i][0], i); } int[] res = new int[intervals.length]; for(int i = 0; i < intervals.length; i++){ Integer key = map.ceilingKey(intervals[i][1]); res[i] = (key == null) ? -1:map.get(key); } return res; }

1471. The k Strongest Values in an Array

public int[] getStrongest(int[] arr, int k) { Arrays.sort(arr); int m = arr[(arr.length - 1) / 2]; int[] ans = new int[k]; int left = 0, right = arr.length - 1; int index = 0; while (index < k) { if (m - arr[left] > arr[right] - m) { ans[index++] = arr[left++]; } else { ans[index++] = arr[right--]; } } return ans; }

1915. Number of Wonderful Substrings Medium 847 54 Companies A wonderful string is a string where at most one letter appears an odd number of times. For example, "ccjjc" and "abab" are wonderful, but "ab" is not. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string.

public long wonderfulSubstrings(String word) { long cnt[] = new long[1024], res = 0; int mask = 0; cnt[0] = 1; for (var ch : word.toCharArray()) { mask ^= 1 << (ch - 'a'); res += cnt[mask]; for (var n = 0; n < 10; ++n) res += cnt[mask ^ (1 << n)]; ++cnt[mask]; } return res;

1508. Range Sum of Sorted Subarray Sums Medium 842 141 Companies You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.

public static int rangeSum(int[] nums, int n, int left, int right) { int[] result = new int[(n * (n + 1) / 2) + 1]; result[0] = 0; result[1] = nums[0]; int k = 0; for (int j = 2, i = 1; j < result.length;) { if (i == nums.length) { k++; i = k; result[j++] = nums[i++]; } else { result[j] = nums[i] + result[j - 1]; j++; i++; } } Arrays.sort(result); int sum = 0; while (left <= right) { sum = (sum + result[left++]) % 1000000007; } return sum; }

Use String Tokenizer countToken method

public static void main(String[] args){ String s = "hello-hi-educative"; StringTokenizer stringTokenizer = new StringTokenizer(s, "-"); int tokenCount = stringTokenizer.countTokens(); for(int i=0;i<tokenCount; i++){ System.out.println("Token [" + i + "] - " + stringTokenizer.nextToken()); } }

1404. Number of Steps to Reduce a Number in Binary Representation to One Medium 707 55 Companies Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules: If the current number is even, you have to divide it by 2. If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test cases.

ublic int numSteps(String s) { int countSteps = 0; int carry = 0; for(int i = s.length()-1;i>=1;i--) { int rightMostBit = s.charAt(i)-'0'; if((rightMostBit+carry) == 1) { carry=1; countSteps += 2; } else { countSteps++; } } return countSteps+carry; }


Conjuntos de estudio relacionados

Primera Guerra Mundial (Cap. 14)

View Set

COMM 331 Organizational Communication

View Set

questions i keep freakin missing pt 2 2019

View Set

Legal Environment of Business 1-28 Final

View Set

Unit 25: Contract Forms for Real Estate Practice in Georgia

View Set

Life Insurance Policies-Provisions, options and Riders Chapter 3

View Set

Communication in Healthcare: Mindfulness: Mindfulness & Reflection, Implicit Bias

View Set

CRWT: CHARACTERISTICS OF A CRITICAL THINKER

View Set

Module 11: Organizing for Long-Term Success

View Set