703321. Fill array with 1's

Medium

Fill Array with 1's

Summary

Given an array of integers, fill it with 1's. This problem is about manipulating arrays and has no specific tags indicating dynamic programming or trees, so we can assume a general algorithmic problem.

Detailed Explanation

The approach to solve this problem involves iterating through the array and assigning each element a value of 1. The step-by-step breakdown of the solution is as follows:

  1. Initialize an integer variable n with the length of the input array.
  2. Create a loop that runs from 0 to n-1.
  3. Inside the loop, assign the value 1 to each element in the array at index i, where i is the current iteration.
  4. After the loop finishes, return the filled array.

The time complexity of this solution is O(n), where n is the length of the input array, as we are performing a single pass through the array. The space complexity is also O(1) because we only use a constant amount of space to store the array and variable n.

Here's an ASCII art diagram showing the filled array:

[1, 1, 1, ..., 1]

Optimized Solutions

Java

View on GeeksforGeeks
public int[] fillArrayWithOnes(int n) {
    int[] arr = new int[n];
    for (int i = 0; i < n; i++) {
        arr[i] = 1;
    }
    return arr;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.