Find the Maximum Number of Marked Indices — LeetCode 2576 Python Solution

MediumGreedyArrayTwo PointersBinary SearchSorting
Problem
#2576
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. Initially, all of the indices are unmarked.

Example

Input
nums = [3,5,2,4]
Output
2
Explanation
In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1.

Python solution

Python
class Solution:
    def maxNumOfMarkedIndices(self, nums: List[int]) -> int:
        nums.sort()
        i, n = 0, len(nums)
        for x in nums[(n + 1) // 2 :]:
            if nums[i] * 2 <= x:
                i += 1
        return i * 2

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2576. Find the Maximum Number of Marked Indices is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2576. Find the Maximum Number of Marked Indices?
LeetCode 2576. Find the Maximum Number of Marked Indices is rated Medium on LeetCode.
What is the time complexity of LeetCode 2576. Find the Maximum Number of Marked Indices?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2576. Find the Maximum Number of Marked Indices?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2576. Find the Maximum Number of Marked Indices cover?
LeetCode 2576. Find the Maximum Number of Marked Indices is tagged Greedy, Array, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview