Skip to main content

Character Pair Proximity Finder

easy
StringTwo PointersTwo Pointer Pair Sum
Asked atAmazonBloomberg

Problem Description

Given a string `text` and a character `target`, find the shortest distance between any two adjacent (in order) occurrences of `target` in `text`. Return that minimum distance. If `target` appears fewer than twice, return `-1`.

The distance between two occurrences at indices `i` and `j` (i < j) is defined as `j - i`.

**Example 1:**
```
Input: text = "blackboard", target = 'b'
Output: 9
Explanation: 'b' appears at indices 0 and 9. Distance = 9.
```

**Example 2:**
```
Input: text = "abracadabra", target = 'a'
Output: 2
Explanation: 'a' appears at indices 0,2,4,6,8,10. Adjacent distances: 2,2,2,2,2. Minimum = 2.
```

Constraints

  • 1 <= text.length <= 10^5
  • target is a single lowercase or uppercase English letter
  • text consists of printable ASCII characters

Follow-up

Extend the solution to return the minimum distance between any two distinct characters chosen from a given set.

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.