↓Skip to main content
  1. LeetCode/

LeetCode 1184: Distance Between Bus Stops

·1 min· ·
LeetCode Easy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-10-18

  • Submissions: Wrong Answer ×4 → Accepted ×4

Approach
#

A ring has only two routes: clockwise covers distance[a:b] (with a = min(start, destination) and b = max(...)), counterclockwise is total - clockwise; take the shorter. Order the endpoints first, or the slice is empty when start > destination.

My Attempts
#

The first four ignored start > destination, so distance[start:destination] was empty and the clockwise distance came out 0: [2, 2], start = 1, destination = 0 returned 0 instead of 2. Adding the swap passed.

Solution
#

class Solution:
    def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
        a, b = min(start, destination), max(start, destination)
        clockwise = sum(distance[a:b])
        return min(clockwise, sum(distance) - clockwise)

Complexity
#

Time O(n), space O(1) apart from the O(n) slice.

Mistakes to Avoid
#

  • start may exceed destination; swap first.

Interview Explanation
#

A ring has two directions; I order the endpoints, take the clockwise sum between them and the total minus it, and return the smaller. Time O(n).

Related

LeetCode 1089: Duplicate Zeros
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 1089 note: count the zeros to know each value’s shift, then move from back to front, writing the extra 0 when copying a zero
LeetCode 1122: Relative Sort Array
·1 min
LeetCode Easy Array Hash-Table Sorting Counting-Sort
LeetCode 1122 note: count first, emit values in arr2’s order, then append the remaining values in ascending order
LeetCode 1128: Number of Equivalent Domino Pairs
·2 mins
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 note: normalize each domino to (small, large) as a key and count; a key with c dominoes yields c(c - 1) / 2 pairs
LeetCode 1030: Matrix Cells in Distance Order
·2 mins
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 note: list every coordinate and sort by Manhattan distance to the center; return coordinates, not distances
LeetCode 1046: Last Stone Weight
·2 mins
LeetCode Easy Array Heap-Priority-Queue
LeetCode 1046 note: from a max-heap (negated values) take the two heaviest each round, push back their difference if unequal, and return the last stone or 0
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand