Do anything with Arrays
Nidhin BM
Posted on June 11, 2023
This post will be updated regularly as I learn
Loop Through Array
let i = 0; i < nums.length; i++
Problem 1: Maximum Consecutive Ones
Input: nums = [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.
Knowledge Check - JavaScript
-
Math.max(result, count)
=> Keep counter updated with max value -
arr.length
=> Used to loop an array
Solution - JavaScript
var findMaxConsecutiveOnes = function(nums) {
let count = 0;
let result = 0;
for (let i = 0; i < nums.length; i++) {
// Reset count when 0 is found
if (nums[i] == 0)
count = 0;
// If 1 is found, increment
else {
// increase count
count++;
result = Math.max(result, count);
}
}
return result;
};
Solution - Java
Math.max(result, count)
and arr.length
are in java too 🤯
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0; //initialize count
int result = 0; //initialize max
for (int i = 0; i < nums.length; i++)
{
// Reset count when 0 is found
if (nums[i] == 0)
count = 0;
// If 1 is found, increment count
else
{
count++;//increase count
result = Math.max(result, count);
}
}
return result;
}
}
Problem 2 : Find Numbers with Even Number of Digits
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Knowledge Check - JavaScript
-
Math.floor(n / 10)
- Can be used for count digits until it becomes 0 -
Math.floor(numberOfDigits % 2) == 0
- Checking for even
Solution - Javascript
var findNumbers = function(nums) {
let result = 0
// loop through numbers
for (let i = 0; i < nums.length; i++){
// find number of digits
const num = nums[i]
const numberOfDigits = countDigit(num)
const isEven = Math.floor(numberOfDigits % 2) == 0
// if even increse counter
isEven && result ++
}
return result
};
function countDigit(n){
let count = 0;
while (n != 0) {
n = Math.floor(n / 10);
count ++;
}
return count;
}
Sorting an array
-
arr.sort((a, b)=>{return a - b})
can be used for numeric sorting (By default, the sort() function sorts values as strings.)
Squares of a Sorted Array
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].
var sortedSquares = function(nums) {
let squaredArray = []
for (let i =0 ; i < nums.length; i++){
const num = nums[i]
const square = num * num
squaredArray.push(square)
}
const result = squaredArray.sort((a, b)=>{return a - b})
return result
};
💖 💪 🙅 🚩
Nidhin BM
Posted on June 11, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.