Taro Logo

Maximum Points Inside the Square

Medium
Asked by:
HashedIn
0 views
Topics:
ArraysBinary SearchStrings

You are given a 2D array points and a string s where, points[i] represents the coordinates of point i, and s[i] represents the tag of point i.

A valid square is a square centered at the origin (0, 0), has edges parallel to the axes, and does not contain two points with the same tag.

Return the maximum number of points contained in a valid square.

Note:

  • A point is considered to be inside the square if it lies on or within the square's boundaries.
  • The side length of the square can be zero.

Example 1:

Input: points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"

Output: 2

Explanation:

The square of side length 4 covers two points points[0] and points[1].

Example 2:

Input: points = [[1,1],[-2,-2],[-2,2]], s = "abb"

Output: 1

Explanation:

The square of side length 2 covers one point, which is points[0].

Example 3:

Input: points = [[1,1],[-1,-1],[2,-2]], s = "ccd"

Output: 0

Explanation:

It's impossible to make any valid squares centered at the origin such that it covers only one point among points[0] and points[1].

Constraints:

  • 1 <= s.length, points.length <= 105
  • points[i].length == 2
  • -109 <= points[i][0], points[i][1] <= 109
  • s.length == points.length
  • points consists of distinct coordinates.
  • s consists only of lowercase English letters.

Solution


Brute Force Solution

Approach

A square centered at the origin with side length 2r covers all points whose maximum absolute coordinate value is at most r. We can compute this Chebyshev distance for each point and group their tags by this distance. By inspecting each layer of points sorted by distance, we can determine the maximum boundary size that does not contain duplicate tags.

Here's how the algorithm would work step-by-step:

  1. Calculate the Chebyshev distance, max(|x|, |y|), for every point to determine which square boundary it lies on.
  2. Group the tags of the points by their corresponding distance in a dictionary.
  3. Sort the unique distances in ascending order to evaluate squares from smallest to largest.
  4. For each distance layer, verify if any tag in the layer is already seen or appears multiple times within the layer.
  5. If a duplicate tag is found, terminate and return the count of points processed so far.
  6. Otherwise, add all tags from the current layer to the set of seen tags and increment the total count of valid points.

Code Implementation

def max_points_inside_square(points: list[list[int]], s: str) -> int:
    # Group points by the Chebyshev distance from the origin
    distance_to_tags = {}
    for index, coordinate in enumerate(points):
        distance = max(abs(coordinate[0]), abs(coordinate[1]))
        tag = s[index]
        if distance not in distance_to_tags:
            distance_to_tags[distance] = []
        distance_to_tags[distance].append(tag)
    
    # Process distances in ascending order to find the largest valid square
    seen_tags = set()
    total_points = 0
    for distance in sorted(distance_to_tags.keys()):
        current_tags = distance_to_tags[distance]
        tag_counts = set()
        has_duplicate = False
        
        # Check if the current boundary introduces duplicate tags
        for tag in current_tags:
            if tag in seen_tags or tag in tag_counts:
                has_duplicate = True
                break
            tag_counts.add(tag)
            
        # Stop if any duplicate is found, otherwise include all points at this distance
        if has_duplicate:
            break
        seen_tags.update(tag_counts)
        total_points += len(current_tags)
        
    return total_points

Big(O) Analysis

Time Complexity
O(N log N) – Calculating distances takes O(N) time. Sorting the unique distances takes O(U log U) where U <= N is the number of unique distances. Checking tags across all layers takes O(N) time in total.
Space Complexity
O(N) – We store each point's tag grouped by distance in a dictionary and maintain a set of seen tags, both taking O(N) auxiliary space.

Optimal Solution

Approach

To find the maximum number of valid points inside a square centered at the origin, we can examine the points in order of their distance from the center. By organizing the points from closest to furthest, we can systematically test larger square sizes while ensuring we never capture two points with the same tag.

Here's how the algorithm would work step-by-step:

  1. Look at all the items scattered around and figure out how far each one is from the exact center point.
  2. Imagine expanding a box outward from the center, and figure out the minimum size the box needs to be to just barely touch each item.
  3. Sort all the items based on how large the box needs to be to capture them, starting with the closest items and moving outward.
  4. Go through the sorted items one by one, imagining the box growing large enough to capture each new item in turn.
  5. Keep track of the tags or labels associated with each item as you include them inside the growing box.
  6. If you ever encounter a new item that shares a tag with an item you have already successfully captured, stop immediately because the rules have been broken.
  7. The maximum number of items you successfully captured right before the stop condition occurred is your final answer.

Code Implementation

class Solution:
    def maxPointsInsideSquare(self, point_coordinates: list[list[int]], point_tags: str) -> int:
        # We calculate the minimum square boundary size for each point using Chebyshev distance.
        point_distances = []
        for point_index, (coord_x, coord_y) in enumerate(point_coordinates):
            distance_size = max(abs(coord_x), abs(coord_y))
            point_distances.append((distance_size, point_tags[point_index]))

        point_distances.sort(key=lambda item: item[0])

        seen_point_tags = set()
        maximum_points_count = 0

        current_distance_index = 0
        total_points_quantity = len(point_distances)

        while current_distance_index < total_points_quantity:
            distance_group_end = current_distance_index
            while distance_group_end < total_points_quantity and point_distances[distance_group_end][0] == point_distances[current_distance_index][0]:
                distance_group_end += 1

            # We process points at the same distance together to handle simultaneous square boundaries correctly.
            batch_has_duplicate = False
            for scan_index in range(current_distance_index, distance_group_end):
                current_tag = point_distances[scan_index][1]
                if current_tag in seen_point_tags:
                    batch_has_duplicate = True
                seen_point_tags.add(current_tag)

            # If duplicate tags appear at this distance, we must halt before adding this batch.
            if batch_has_duplicate:
                break

            maximum_points_count = distance_group_end
            current_distance_index = distance_group_end

        return maximum_points_count

Big(O) Analysis

Time Complexity
O(n log n) – Calculating the distance for each of the n points takes linear time, while sorting these points based on their distance drives the primary cost at O(n log n time). Iterating through the sorted points to check and record their tags takes a single pass, which is linear in n. The sorting step dominates the total operations, approximately n * log(n) steps, which simplifies to O(n log n).
Space Complexity
O(N) – To determine the space complexity, let N represent the total number of points given in the input. The algorithm requires auxiliary data structures, specifically a sorting buffer or list to store the calculated distances and tags for all N items, and a hash map or tracking set that can hold at most N unique tags during the traversal. As the input size N increases, the extra memory consumed by these tracking collections and sorting operations grows linearly. Thus, the total auxiliary space complexity simplifies to Big O of N.

Edge Cases

Points located exactly on the edges or corners of the expanding square
How to Handle:
We consider a point inside the square if its Chebyshev distance, which is the maximum of the absolute x and y coordinates, is less than or equal to the square's half-side length.
Duplicate tags assigned to different points inside or on the expanding square
How to Handle:
We track seen tags using a set or boolean array to ensure only points with strictly unique tags contribute to the count before a duplicate tag blocks further expansion.
Points with negative coordinates in one or more quadrants
How to Handle:
We take the absolute values of both x and y coordinates for every point to compute its minimum required square size correctly regardless of quadrant.
Points located at the exact origin where coordinates are zero
How to Handle:
A distance of zero is handled naturally as the square can start at size zero and include these points without violating uniqueness constraints.
Extremely large coordinate values approaching integer limits
How to Handle:
Using 64-bit integers for distance calculations prevents potential arithmetic overflow when evaluating extreme boundary values.
Single point provided in the input arrays
How to Handle:
The algorithm processes the single point, checks its tag validity, and returns a count of one assuming it fits within the square.
Multiple points sharing the exact same minimum distance from the origin with different tags
How to Handle:
We process points in increasing order of their maximum coordinate distance and stop or fail the count only when a duplicate tag is encountered among points at the exact same distance boundary.
Large scale inputs with tens of thousands of points
How to Handle:
Sorting the points by their maximum coordinate distance ensures an efficient time complexity well within typical interview execution limits.