700269. Replace all 0's with 5
Basic
Replace all 0's with 5
Summary
Given an array, replace all occurrences of 0 with 5. This problem is about basic array manipulation and requires a straightforward approach.
Detailed Explanation
We can solve this problem by iterating through the array and replacing each occurrence of 0 with 5. Here's a step-by-step breakdown:
- Initialize an empty array
resultto store the modified elements. - Iterate through the original array using a for loop or any other suitable method (e.g., foreach in some languages).
- For each element, check if it is equal to 0.
- If the element is 0, replace it with 5 in the
resultarray. - Continue this process until all elements have been processed.
- Return or print the modified
resultarray.
Time complexity: O(n), where n is the size of the input array. Space complexity: O(n) for storing the modified array.
Optimized Solutions
Java
public int[] replaceZeroWithFive(int[] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
result[i] = 5;
} else {
result[i] = arr[i];
}
}
return result;
}