Classify Numbers with an isEven Function
Solve this ProblemEasy10 min
Topics
BasicsFunctionsArrays
Companies
TCSInfosysWipro
Given an array
nums, return a list of the same length with the label "even" or "odd" for each number.
Checking one number's parity is covered in the Conditionals section; here the focus is on turning that check into a helper functionHelper FunctionA small function that does one focused job for another function, such as isEven(n). that returns a booleanBooleanA value that is either true or false.. Writing the question "is this even?" once and calling it by name keeps the loop short and makes the same check reusable elsewhere.
Test Case 1:
Input:nums = [4, 7, 0, -3]
Output:["even", "odd", "even", "odd"]
Explanation:0 is even, and so is any number divisible by 2; −3 leaves a remainder, so it is odd.
Test Case 2:
Input:nums = [10]
Output:["even"]
Explanation:One number, one label.
Constraints
- ◆
1 ≤ nums.length ≤ 50 - ◆
-1000000 ≤ nums[i] ≤ 1000000
Try the Dry Run
Approach & Solutions
Inline Modulo CheckGood
Walk through the array and, for each value, test value % 2 == 0 right inside the loop. Even values get the label "even", the rest "odd". The test is written directly where it is used.
Time
O(n)Space
O(n) for the outputJava
class Solution {
public String[] labelParity(int[] nums) {
String[] labels = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
labels[i] = "even";
} else {
labels[i] = "odd";
}
}
return labels;
}
}Reusable isEven() HelperOptimal
Move the test into its own function, isEven(n), which returns a boolean. The loop then reads almost like English: label each value "even" if isEven(value), otherwise "odd". The helper can be reused anywhere else that needs the same check.
Time
O(n)Space
O(n) for the outputJava
class Solution {
boolean isEven(int n) {
return n % 2 == 0;
}
public String[] labelParity(int[] nums) {
String[] labels = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
labels[i] = isEven(nums[i]) ? "even" : "odd";
}
return labels;
}
}