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:

  1. Initialize an empty array result to store the modified elements.
  2. Iterate through the original array using a for loop or any other suitable method (e.g., foreach in some languages).
  3. For each element, check if it is equal to 0.
  4. If the element is 0, replace it with 5 in the result array.
  5. Continue this process until all elements have been processed.
  6. Return or print the modified result array.

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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.