Skip to main content

Command Palette

Search for a command to run...

first and last

Published
1 min readView as Markdown

import java.util.Arrays;

public class fl {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 3, 3, 4, 5, 6};
        int target = 3;

        int first = findFirst(arr, target);
        int last = findLast(arr, target);

        System.out.println(first);
        System.out.println(last);
    }

    static int findFirst(int[] arr, int target) {
        int low = 0, high = arr.length - 1, ans = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == target) {
                ans = mid;
                high = mid - 1; // go left for first occurrence
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return ans;
    }

    static int findLast(int[] arr, int target) {
        int low = 0, high = arr.length - 1, ans = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == target) {
                ans = mid;
                low = mid + 1; // go right for last occurrence
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return ans;
    }
}

More from this blog

Amit singh's blog

235 posts