Member-only story

CS Interview Prep: Partition Labelling — Leetcode

janac
3 min readMay 22, 2020

--

Question from here: https://leetcode.com/problems/partition-labels/

Problem Statement

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:

Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.

Constraints:

  1. S will have length in range [1, 500].
  2. S will consist of lowercase letters ('a' to 'z') only.

How to approach this question

This question becomes less confusing when you realize three facts

  1. The constraint is actually a hint: s will only consist of lowercase letters
  2. Lowercase letters are of type char which means they have a codepoint. A codepoint is a numerical representation of a char, as defined by its UTF-8 encoding.
  3. There are 26 letters in the English alphabet
  4. You can add and subtract chars, which implicitly is adding and subtracting their codepoints

--

--

janac
janac

Written by janac

Most of my writing is about software. I enjoy summarizing and analyzing books and self-help videos. I am senior software consultant at LazerTechnologies.com.

No responses yet