703221. Last index of One

Basic

Last Index of One

Summary

Given an array of integers, find the last index at which a 1 appears. This problem requires searching through the array to identify the last occurrence of a specific element (in this case, the number 1). The key concepts involved are arrays and searching.

Detailed Explanation

To solve this problem, we can iterate through the array from right to left (i.e., starting from the end). We keep track of the index at which the last 1 is found. If no 1 is found in the array, we return -1.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable last_index to -1.
  2. Iterate through the array from right to left.
  3. For each element, check if it is equal to 1. If it is:
    • Update last_index with the current index.
  4. After iterating through the entire array, return last_index.

The time complexity of this solution is O(n), where n is the size of the input array. The space complexity is O(1), as we only use a constant amount of space to store the last_index variable.

Optimized Solutions

Java

View on GeeksforGeeks
public int lastIndexOne(int[] arr) {
    int last_index = -1;
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == 1) {
            last_index = i;
            break;
        }
    }
    return last_index;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.