Given a string s and a single character c, return a list of integers where each element is the shortest distance from the character at that index to the nearest occurrence of c in s. The character c is guaranteed to appear at least once in s when s is non-empty. Return null for null input.
Examples:
Input: s = 'loveleetcode', c = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Explanation: For each position, find the distance to the closest e
Input: s = 'abcd', c = 'a'
Output: [0, 1, 2, 3]
Explanation: Only one a at index 0, so distances grow toward the right
Input: s = 'abcd', c = 'd'
Output: [3, 2, 1, 0]
Explanation: Only one d at the end, so distances grow toward the left
Input: s = 'a', c = 'a'
Output: [0]
Explanation: Single character that matches the target
Input: s = null, c = 'x'
Output: null
Explanation: Null input returns null
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay July 2026
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.