LeetCode 2089: Find Target Indices After Sorting Array Solution

Master LeetCode problem 2089 (Find Target Indices After Sorting Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2089. Find Target Indices After Sorting Array

Problem Explanation

Explanation

To solve this problem, we can first create a mapping of each element to its original index in the input array. Then, we sort the array in non-decreasing order. After sorting, we iterate through the sorted array and check if the element is equal to the target. If it is, we add the original index of that element to the result list. Finally, we return the result list sorted in increasing order.

  • Time complexity: O(n log n) where n is the number of elements in the array due to sorting.
  • Space complexity: O(n) to store the mapping of each element to its index.

Solution Code

import java.util.*;

class Solution {
    public List<Integer> findTargetIndices(int[] nums, int target) {
        List<Integer> result = new ArrayList<>();
        Map<Integer, Integer> indexMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            indexMap.put(nums[i], i);
        }

        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                result.add(indexMap.get(target));
            }
        }

        Collections.sort(result);
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2089 (Find Target Indices After Sorting Array)?

This page provides optimized solutions for LeetCode problem 2089 (Find Target Indices After Sorting Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2089 (Find Target Indices After Sorting Array)?

The time complexity for LeetCode 2089 (Find Target Indices After Sorting Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2089 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2089 in Java, C++, or Python.

Back to LeetCode Solutions