Leetcode — Easy Problems & Solutions — Amazon (https://leetcode.com/company/amazon/)
905. Sort Array By Parity
Given an array A
of non-negative integers, return an array consisting of all the even elements of A
, followed by all the odd elements of A
.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
class Solution {
public int[] sortArrayByParity(int[] A) {
int[] result = new int[A.length];
Deque<Integer> dq = new ArrayDeque<> ();
for(int i=0;i<A.length;i++){
if(A[i]%2==0)
{
dq.addFirst(A[i]);
}
else{
dq.addLast(A[i]);
}
}
Object[] objArray = dq.toArray();
for(int i=0; i<objArray.length; i++){
result[i] = (int) objArray[i];
}
return result;
}
}
1342. Number of Steps to Reduce a Number to Zero
Given a non-negative integer num
, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
class Solution {
public int numberOfSteps (int num) {
int count=0;
while(num!=0){
if(num%2==0){
num=num/2;
count++;}
else{
num=num-1;
count++;
}
}
return count;
}
}
1365. How Many Numbers Are Smaller Than the Current Number
Given the array nums
, for each nums[i]
find out how many numbers in the array are smaller than it. That is, for each nums[i]
you have to count the number of valid j's
such that j != i
and nums[j] < nums[i]
.
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] arr = new int[nums.length];
for(int i=0;i<nums.length;i++){
int count=0;
for(int j=0;j<nums.length;j++){
if(nums[i]>nums[j])
count=count+1;
}
arr[i]=count;
}
return arr;
}
}
383. Ransom Note
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
- You may assume that both strings contain only lowercase letters.
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
StringBuffer sb = new StringBuffer(magazine);
for(int i=0;i<ransomNote.length();i++){
if(sb.toString().contains(ransomNote.charAt(i)+””)){
sb.deleteCharAt(sb.indexOf(ransomNote.charAt(i)+””));
}
else{
return false;
}
}
return true;
}
}
485. Max Consecutive Ones
(Review this..)
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
- The input array will only contain
0
and1
. - The length of input array is a positive integer and will not exceed 10,000
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums.length==1){
if(nums[0]==0)
return 0;
else
return 1;
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<nums.length;i++){
sb.append(String.valueOf(nums[i]));
}
String str = sb.toString();
if(!str.contains(“1”))
return 0;
String[] str1 = str.split(“0”);
Arrays.sort(str1);
return str1[str1.length-1].length();
}
}
88. Merge Sorted Array
Given two sorted integer arrays nums1
and nums2
, merge nums2
into nums1
as one sorted array.
The number of elements initialized in nums1
and nums2
are m
and n
respectively. You may assume that nums1
has enough space (size that is equal to m + n
) to hold additional elements from nums2
.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Constraints:
0 <= n, m <= 200
1 <= n + m <= 200
nums1.length == m + n
nums2.length == n
-109 <= nums1[i], nums2[i] <= 109
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {for(int i=0;i<n;i++){
nums1[m+i]=nums2[i];
}
Arrays.sort(nums1);
}
}
20. Valid Parentheses
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
class Solution {
public boolean isValid(String s) {
if(s.length() % 2!=0)
return false;
Stack<Character> stack = new Stack();
for(char c : s.toCharArray()){
if(c==’(‘ || c==’{‘ || c==’[‘){
stack.push(c);
}else if(c==’)’ && !stack.isEmpty() && stack.peek()==’(‘){
stack.pop();
}
else if(c==’}’ && !stack.isEmpty() && stack.peek()==’{‘){
stack.pop();
}
else if(c==’]’ && !stack.isEmpty() && stack.peek()==’[‘){
stack.pop();
}
else {
return false ;
}
}
return stack.isEmpty();
}
}
205. Isomorphic Strings
Given two strings s and t, determine if they are isomorphic.
Two strings 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
Example 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length()==0)
return true;
int count=0;
for(int i=0;i<s.length();i++){
if(s.indexOf(s.charAt(i))==t.indexOf(t.charAt(i)))
count=count+1;
}
if(count!=s.length())
return false;
else
return true;
}
}
1086. High Five
Given a list of the scores of different students, items
, where items[i] = [IDi, scorei]
represents one score from a student with IDi
, calculate each student's top five average.
Return the answer as an array of pairs result
, where result[j] = [IDj, topFiveAveragej]
represents the student with IDj
and their top five average. Sort result
by IDj
in increasing order.
A student’s top five average is calculated by taking the sum of their top five scores and dividing it by 5
using integer division.
Example 1:
Input: items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
Output: [[1,87],[2,88]]
Explanation:
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
Example 2:
Input: items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]
Output: [[1,100],[7,100]]
Constraints:
1 <= items.length <= 1000
items[i].length == 2
1 <= IDi <= 1000
0 <= scorei <= 100
- For each
IDi
, there will be at least five scores.
class Solution {
public int[][] highFive(int[][] items) {
HashMap<Integer, ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>();
for(int i=0;i<items.length;i++){
if(hm.containsKey(items[i][0])){
hm.get(items[i][0]).add(items[i][1]);
}
else{
hm.put(items[i][0],new ArrayList<Integer>());
hm.get(items[i][0]).add(items[i][1]);}
}
int i=0;
int[][] a = new int[hm.size()][2];
for(Map.Entry<Integer, ArrayList<Integer>> entry : hm.entrySet()){
int sum=0;
int avg=0;
ArrayList<Integer> al = new ArrayList<Integer>();
al = entry.getValue();
Collections.sort(al);
for(int j=al.size()-1;j>=(al.size()-5);j — ){
sum=sum+al.get(j);
}
avg=sum/5;
a[i][0]=entry.getKey();
a[i][1]=avg;
i++;
}
return a;}
}
463. Island Perimeter
You are given row x col
grid
representing a map where grid[i][j] = 1
represents land and grid[i][j] = 0
represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid
is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn’t have “lakes”, meaning the water inside isn’t connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.
Example 1:
Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image above.
Example 2:
Input: grid = [[1]]
Output: 4
Example 3:
Input: grid = [[1,0]]
Output: 4
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 100
grid[i][j]
is0
or1
.
class Solution {
public int islandPerimeter(int[][] grid) {
int per=0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]==1){
per=per+4;
if(i-1>=0 && grid[i-1][j]==1)
per=per-2;
if(j-1>=0 && grid[i][j-1]==1)
per=per-2;
}
}
}
return per;
}
}
1299. Replace Elements with Greatest Element on Right Side
(solved this. but, failed with error — Time limit Exceeded for the last case. rest all cases are passed. Need to improve performance)
Given an array arr
, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1
.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5
class Solution {
public int[] replaceElements(int[] arr) {
int[] arr1 = new int[arr.length];
int lastbutone = arr[arr.length-1];
if(arr.length==1){
arr1[0]=-1;
return arr1;
}
for(int i=0;i<arr.length-2;i++){
for(int j=0;j<=i;j++){
arr[j]=0;}
int ele = Arrays.stream(arr).max().getAsInt();
arr1[i]=ele;
}
arr1[arr.length-2]=lastbutone;
arr1[arr.length-1]=-1;
return arr1;
}
}
922. Sort Array By Parity II
Given an array A
of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i]
is odd, i
is odd; and whenever A[i]
is even, i
is even.
You may return any answer array that satisfies this condition.
Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
class Solution {
public int[] sortArrayByParityII(int[] A) {
int[] B = new int[A.length];
Stack<Integer> even = new Stack<Integer>();
Stack<Integer> odd = new Stack<Integer>();
for(int i=0;i<A.length;i++){
if(A[i]%2==0 || A[i]%2==2)
even.add(A[i]);
else
odd.add(A[i]);
}
for(int i=0;i<A.length;i++){
if(i%2==0 || i%2==2)
B[i]=even.pop();
else
B[i]=odd.pop();
}
return B;
}
}
1002. Find Common Characters
Given an array A
of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j]
is a lowercase letter
class Solution {
public List<String> commonChars(String[] A) {
String first = A[0];
List<String> li = new ArrayList<String>();
StringBuilder[] sb = new StringBuilder[A.length-1];
for(int i=0;i<sb.length;i++){
sb[i]=new StringBuilder(A[i+1]);
}
for(int i=0;i<first.length();i++){
int count=0;
for(int j=0;j<sb.length;j++)
{
for(int k=0;k<sb[j].length();k++){
if(sb[j].charAt(k)==first.charAt(i)){
sb[j].deleteCharAt(k);
count=count+1;
break;
}
}}
if(count==sb.length)
li.add(first.charAt(i)+””);}
return li;
}
}
977. Squares of a Sorted Array
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.
class Solution {
public int[] sortedSquares(int[] nums) {
int[] squares = new int[nums.length];
for(int i=0;i<nums.length;i++){
squares[i]=nums[i]*nums[i];
}
Arrays.sort(squares);
return squares;
}
}
557. Reverse Words in a String III
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
class Solution {
public String reverseWords(String s) {
String[] str = s.split(“ “);
StringBuilder[] sb = new StringBuilder[s.length()];
StringBuilder sb1 = new StringBuilder(“”);
for(int i=0;i<str.length;i++){
for(int j=str[i].length()-1;j>=0;j — ){
sb1.append(str[i].charAt(j));
}
sb1.append(“ “);
}
return sb1.toString().trim();
}
}
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[]
.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
class Solution {
public void reverseString(char[] s) {
int i=0;
int j=s.length-1;
while(i<s.length/2 && j>=s.length/2){
char temp= s[i];
s[i]=s[j];
s[j]=temp;
i++;
j — ;
}
}
}
136. Single Number
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
- Each element in the array appears twice except for one element which appears only once.
class Solution {
public int singleNumber(int[] nums) {
int num = 0;
int count=0;
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
for(int i=0;i<nums.length-1;i=i+2){
if(nums[i]<nums[i+1]){
System.out.println(nums[i]+” — “+nums[i+1]);
count=count+1;
num= nums[i];
break;}
}
if(count==0)
num=nums[nums.length-1];
return num;
}
}
1351. Count Negative Numbers in a Sorted Matrix
Given a m * n
matrix grid
which is sorted in non-increasing order both row-wise and column-wise.
Return the number of negative numbers in grid
.
Example 1:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.
Example 2:
Input: grid = [[3,2],[1,0]]
Output: 0
Example 3:
Input: grid = [[1,-1],[-1,-1]]
Output: 3
Example 4:
Input: grid = [[-1]]
Output: 1
class Solution {
public int countNegatives(int[][] grid) {
int count =0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]<0)
count=count+1;
}
}
return count;
}
}
359. Logger Rate Limiter
Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t
will prevent other identical messages from being printed until timestamp t + 10
).
All messages will come in chronological order. Several messages may arrive at the same timestamp.
Implement the Logger
class:
Logger()
Initializes thelogger
object.bool shouldPrintMessage(int timestamp, string message)
Returnstrue
if themessage
should be printed in the giventimestamp
, otherwise returnsfalse
.
Example 1:
Input
["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"]
[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]
Output
[null, true, true, false, false, false, true]Explanation
Logger logger = new Logger();
logger.shouldPrintMessage(1, "foo"); // return true, next allowed timestamp for "foo" is 1 + 10 = 11
logger.shouldPrintMessage(2, "bar"); // return true, next allowed timestamp for "bar" is 2 + 10 = 12
logger.shouldPrintMessage(3, "foo"); // 3 < 11, return false
logger.shouldPrintMessage(8, "bar"); // 8 < 12, return false
logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false
logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is
// 11 + 10 = 21
Constraints:
0 <= timestamp <= 109
- Every
timestamp
will be passed in non-decreasing order (chronological order). 1 <= message.length <= 30
- At most
104
calls will be made toshouldPrintMessage
.
class Logger {
HashMap<String, Integer> hm;public Logger() {
hm = new HashMap<String, Integer>();
}
public boolean shouldPrintMessage(int timestamp, String message) {
for (Map.Entry<String, Integer> entry: hm.entrySet()){
}if(hm.containsKey(message)){
if(timestamp-hm.get(message)>=10){
hm.put(message, timestamp);
return true;
}
else{
return false;
}
}
else{hm.put(message, timestamp);
return true;}
}
}
1119. Remove Vowels from a String
Given a string s
, remove the vowels 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
from it, and return the new string.
Example 1:
Input: s = "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: s = "aeiou"
Output: ""
Constraints:
1 <= s.length <= 1000
s
consists of only lowercase English letters.
class Solution {
public String removeVowels(String s) {
String str = s.replaceAll(“[aeiou]”,””);
return str;
}
}
1480. Running Sum of 1d Array
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
class Solution {
public int[] runningSum(int[] nums) {
int[] arr = new int[nums.length];
int ele=0;
for(int i=0;i<nums.length;i++){
ele=ele+nums[i];
arr[i]=ele;
}
return arr;
}
}
1431. Kids With the Greatest Number of Candies
1431. Kids With the Greatest Number of Candies
Easy
556141Add to ListShare
Given the array candies
and the integer extraCandies
, where candies[i]
represents the number of candies that the ith kid has.
For each kid check if there is a way to distribute extraCandies
among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.
Example 1:
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation:
Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids.
Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
Kid 3 has 5 candies and this is already the greatest number of candies among the kids.
Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies.
Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.
Example 2:
Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy.
Example 3:
Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]
class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
int maxEle = Arrays.stream(candies).max().getAsInt();
List<Boolean> li = new ArrayList<Boolean>();
for(int i=0;i<candies.length;i++){
if((candies[i]+extraCandies)>=maxEle)
li.add(true);
else
li.add(false);
}
return li;
}
}
1108. Defanging an IP Address
Given a valid (IPv4) IP address
, return a defanged version of that IP address.
A defanged IP address replaces every period "."
with "[.]"
.
Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
Constraints:
- The given
address
is a valid IPv4 address.
class Solution {
public String defangIPaddr(String address) {
String str = address.replaceAll(“\\.”,”[.]”);
return str;
}
}
1512. Number of Good Pairs
Given an array of integers nums
.
A pair (i,j)
is called good if nums[i]
== nums[j]
and i
< j
.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
class Solution {
public int numIdenticalPairs(int[] nums) {
int count=0;
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]==nums[j])
count=count+1;
}
}
return count;
}
}
771. Jewels and Stones
You’re given strings jewels
representing the types of stones that are jewels, and stones
representing the stones you have. Each character in stones
is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.
Example 1:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ"
Output: 0
Constraints:
1 <= jewels.length, stones.length <= 50
jewels
andstones
consist of only English letters.- All the characters of
jewels
are unique.
class Solution {
public int numJewelsInStones(String J, String S) {
int count = 0;
for(int i=0;i<J.length();i++){
for(int j=0;j<S.length();j++){
if(J.charAt(i)==S.charAt(j))
count=count+1;
}
}
return count;
}
}
1603. Design Parking System
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the ParkingSystem
class:
ParkingSystem(int big, int medium, int small)
Initializes object of theParkingSystem
class. The number of slots for each parking space are given as part of the constructor.bool addCar(int carType)
Checks whether there is a parking space ofcarType
for the car that wants to get into the parking lot.carType
can be of three kinds: big, medium, or small, which are represented by1
,2
, and3
respectively. A car can only park in a parking space of itscarType
. If there is no space available, returnfalse
, else park the car in that size space and returntrue
.
Example 1:
Input
["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
[[1, 1, 0], [1], [2], [3], [1]]
Output
[null, true, true, false, false]Explanation
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
Constraints:
0 <= big, medium, small <= 1000
carType
is1
,2
, or3
- At most
1000
calls will be made toaddCar
class ParkingSystem {
int big, medium, small;
public ParkingSystem(int big, int medium, int small) {
this.big=big;
this.medium=medium;
this.small=small;
}
public boolean addCar(int carType) {
if(carType==1 && big==0 || carType==2 && medium==0 || carType==3 && small==0)
return false;
if(carType==1)
big — ;
if(carType==2)
medium — ;
if(carType==3)
small — ;
return true;
}
}
1025. Divisor Game
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N
on the chalkboard. On each player's turn, that player makes a move consisting of:
- Choosing any
x
with0 < x < N
andN % x == 0
. - Replacing the number
N
on the chalkboard withN - x
.
Also, if a player cannot make a move, they lose the game.
Return True
if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Note:
1 <= N <= 1000
class Solution {
public boolean divisorGame(int N) {
if(N%2==0)
return true;
else
return false;
}
}