Finding 3-Digit Even Numbers LeetCode solution in Java

1
/*
2

3
As we know that we want unique numbers of 3 digits only that too only even. so first we
4
gather the frequency of all the digits we have, then we iterate from 100 to 999 ( all possible 3 digits numbers, 100,102,104...
5
all possible even 3 digit numbers). for ex we are iterating and we are
6
at 104 so we will see that if we have digits
7
1,0,4 in our database if yes then we can make this number from our
8
available digits given to us.
9

10

11
Time complexity : O(digits.length) // due to making of frequency map
12
Space Complexity : O(1) //fixed map array space for digits 0 to 9
13
*/
14

15
class Solution {
16
public int[] findEvenNumbers(int[] digits) {
17
int[] map = new int[10]; // for freq of 0 to 9 (digits are fixed)
18

19
for (int i = 0; i < digits.length; i++) { // make a frequency map of digits
20
map[digits[i]]++;
21
}
22

23
List<Integer> arr = new ArrayList<>();
24

25
for (int i = 100; i <= 999; i = i + 2) { // will always runs from 100 to 999
26
int num = i;
27
int[] freq = new int[10];
28
while (num > 0) { // will always run 3 times
29
int rem = num % 10;
30
freq[rem]++;
31
num = num / 10;
32
}
33

34
boolean res = findans(freq, map);
35
if (res) arr.add(i);
36
}
37

38
int[] ans = new int[arr.size()]; // logic for arraylist to array conversion
39
for (int i = 0; i < arr.size(); i++) { // at max we can have all num from 100 to 998 only
40
ans[i] = arr.get(i);
41
}
42

43
return ans;
44
}
45

46
private boolean findans(int[] currentNum, int[] database) {
47

48
for (int i = 0; i < 10; i++) { // it will always run for at max 10 times
49
if (currentNum[i] > database[i]) return false;
50
}
51
return true;
52
}
53
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0