702698. Last seen array element

Easy

Here is a detailed Markdown blog post for the "Last seen array element" problem:

Last Seen Array Element

Summary

The problem is about finding the last seen array element in an unsorted array. This involves iterating through the array and keeping track of the most recent element encountered.

Detailed Explanation

To solve this problem, we can iterate through the array from start to end, updating a variable each time we encounter a new maximum value. At the end of the iteration, the last seen array element will be stored in the variable.

Here is a step-by-step breakdown of the solution:

  1. Initialize a variable last_seen to store the last seen array element.
  2. Iterate through the array from start to end.
  3. For each element, check if it is greater than the current value of last_seen.
  4. If the element is greater, update last_seen with its value.
  5. After iterating through the entire array, last_seen will hold the last seen array element.

Time complexity: O(n), where n is the size of the array. Space complexity: O(1), as we only use a constant amount of space to store the last_seen variable.

Optimized Solutions

Java

java
public class LastSeenArrayElement {
    public static int findLastSeen(int[] arr) {
        int last_seen = Integer.MIN_VALUE;
        for (int i : arr) {
            if (i > last_seen) {
                last_seen = i;
            }
        }
        return last_seen;
    }
}

Python

python
def find_last_seen(arr):
    last_seen = float('-inf')
    for i in arr:
        if i > last_seen:
            last_seen = i
    return last_seen

C++

cpp
#include <iostream>
int findLastSeen(int arr[], int n) {
    int last_seen = INT_MIN;
    for (int i = 0; i < n; i++) {
        if (arr[i] > last_seen) {
            last_seen = arr[i];
        }
    }
    return last_seen;
}

JavaScript

javascript
function findLastSeen(arr) {
    let last_seen = -Infinity;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] > last_seen) {
            last_seen = arr[i];
        }
    }
    return last_seen;
}
View on GeeksforGeeks

Not available

DevExCode

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

© 2026 DevExCode. All rights reserved.