LeetCode: Shortest Distance To A Character Solution

Approach

Create array of c's indexes

Ưith each char, find min of diff array from c's indexes

Implementation

1/**
2 * @param {string} s
3 * @param {character} c
4 * @return {number[]}
5 */
6var shortestToChar = function (s, c) {
7 const chars = s.split("")
8 const cIdxes = chars.reduce(
9 (acc, el, idx) => (el === c ? [...acc, idx] : acc),
10 []
11 )
12 return chars.map((_, idx) =>
13 Math.min.apply(
14 null,
15 cIdxes.map(cIdx => Math.abs(idx - cIdx))
16 )
17 )
18}

Comments

Loading comments...

Tags

leetcode

array

string

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: 3sum

HoningJS

Search Posts