Similar Problems

Similar Problems not available

Find Target Indices After Sorting Array - Leetcode Solution

Companies:

LeetCode:  Find Target Indices After Sorting Array Leetcode Solution

Difficulty: Easy

Topics: sorting binary-search array  

Problem Statement:

Given an array of integers nums and a target value target, find the indices of the elements in nums that sum up to target after sorting the array in ascending order.

Example:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: The nums[0] + nums[1] = 2 + 7 = 9, so the indices 0 and 1 are returned.

Solution:

To solve this problem we can start by creating a dictionary that will contain the values of nums as keys and their indices as values. Then, we can sort the nums array in ascending order. After that, we can loop through the sorted nums array and for each element, we can check if the difference between target and the element is present in the dictionary or not. If it is present, then we can return the indices of the current element and the element with the difference.

Here is the Python code for the same:

class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) num_index = {}

# creating dictionary with nums value and indices
for i in range(n):
  num_index[nums[i]] = i

# sorting nums array in ascending order
nums.sort()

# looping through sorted nums array
for i in range(n):
  # checking if the difference between target and the current element is present
  if target - nums[i] in num_index:
    return [i, num_index[target - nums[i]]]

return [-1,-1]

Time Complexity:

The time complexity of this algorithm is O(nlogn) because of sorting the nums array and O(n) for looping through the sorted array. Thus, the overall time complexity is O(nlogn).

Space Complexity:

The space complexity of this algorithm is O(n) because of creating the num_index dictionary to store the values of nums and their indices.

Overall, this algorithm will work efficiently for large inputs as well because of its time complexity of O(nlogn).

Find Target Indices After Sorting Array Solution Code

1