{"id":10083,"date":"2025-09-19T19:57:01","date_gmt":"2025-09-19T14:27:01","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=10083"},"modified":"2025-09-19T20:30:44","modified_gmt":"2025-09-19T15:00:44","slug":"partition-labels","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/partition-labels\/","title":{"rendered":"Partition Labels"},"content":{"rendered":"\n<!-- merge_7-->\n<!-- PrismJS for Syntax Highlighting -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\" rel=\"stylesheet\">\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n  <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n  <h1 class=\"wp_blog_main-heading\"><\/h1>\n\n  <div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n    <p>\n        You are given a string <code>s<\/code>. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string <code>\"ababcc\"<\/code> can be partitioned into <code>[\"abab\", \"cc\"]<\/code>, but partitions such as <code>[\"aba\", \"bcc\"]<\/code> or <code>[\"ab\", \"ab\", \"cc\"]<\/code> are invalid.\n    <\/p>\n\n    <p>\n        <strong>\n            Note that the partition is done so that after concatenating all the parts in order, the resultant string should be <code>s<\/code>.\n        <\/strong>\n    <\/p>\n\n    <p>Return a <i>list of integers representing the size of these parts.<\/i><\/p>\n    \n\n    <h3>Example 1:<\/h2>\n    <p><strong>Input:<\/strong> s = &#8220;ababcbacadefegdehijhklij&#8221;\n<\/p>\n    <p><strong>Output:<\/strong> [9,7,8]<\/p>\n    <p><strong>Explanation:<\/strong>\n        The partition is &#8220;ababcbaca&#8221;, &#8220;defegde&#8221;, &#8220;hijhklij&#8221;.\n        This is a partition so that each letter appears in at most one part.\n        A partition like &#8220;ababcbacadefegde&#8221;, &#8220;hijhklij&#8221; is incorrect, because it splits s into less parts.\n    <\/p>\n\n    <h3>Example 2:<\/h3>\n    <p><strong>Input: <\/strong>s = &#8220;eccbbbbdec&#8221;<\/p>\n    <p><strong>Output: <\/strong>[10]<\/p>\n\n    <!-- <h3>Example 3:<\/h3>\n    <p><strong>Input: <\/strong>intervals = [[4,7],[1,4]]<\/p>\n    <p><strong>Output: <\/strong>[[1,7]]<\/p>\n    <p><strong>Explanation: <\/strong>\n       Intervals [1,4] and [4,7] are considered overlapping.\n    <\/p> -->\n\n    <h3>Constraints<\/h3>\n    <ul>\n        <li><code>1 <= intervals.length <= 10<sup>4<\/sup><\/code><\/li>\n        <li><code>intervals[i].length == 2<\/code><\/li>\n        <li><code>0 <= start<sub>i<\/sub> <= end<sub>i<\/sub><= 10<sup>5<\/sup><\/code><\/li>\n    <\/ul>\n<h2>Approach:<\/h2>\n   <ul>\n        <li>For <code>each character<\/code>, record its last occurrence in the <strong>string<\/strong>.<\/li>\n        <li><code>Traverse the string<\/code> while keeping track of the <strong>current partition end<\/strong> (max last index seen so far).<\/li>\n        <li>Whenever the <strong>current index equals this partition end<\/strong>, we close the partition and record its size.<\/li>\n    <\/ul>\n\n    <h2>Time &#038; Space Complexity:<\/h2>\n    <p><strong>Time Complexity:<\/strong> <code>O(n)<\/code><\/p>\n    <p><strong>Space Complexity:<\/strong> <code>O(1)<\/code><\/p>\n\n<h2>Dry Run<\/h2> <div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\"> <p><strong>Input:<\/strong> <code>s = \"ababcbacadefegdehijhklij\"<\/code><\/p> <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\"> Step 0: Start Function: partitionLabels(s) s = \"ababcbacadefegdehijhklij\" ans = [] first = Array(26).fill(-1) last = Array(26).fill(-1) ------------------------------------------------------------ Step 1: Fill first[] and last[] arrays 'a' \u2192 first[a]=0, last[a]=8 'b' \u2192 first[b]=1, last[b]=5 'c' \u2192 first[c]=4, last[c]=7 'd' \u2192 first[d]=9, last[d]=14 'e' \u2192 first[e]=10, last[e]=15 'f' \u2192 first[f]=11, last[f]=11 'g' \u2192 first[g]=13, last[g]=13 'h' \u2192 first[h]=16, last[h]=19 'i' \u2192 first[i]=17, last[i]=22 'j' \u2192 first[j]=18, last[j]=23 'k' \u2192 first[k]=20, last[k]=20 'l' \u2192 first[l]=21, last[l]=21 (others remain -1) ------------------------------------------------------------ Step 2: Partition calculation Initialize partitionStart = 0, partitionEnd = 0 Iteration (i = 0, s[i]='a'): partitionEnd = max(0, 8) = 8 Iteration (i = 1, s[i]='b'): partitionEnd = max(8, 5) = 8 Iteration (i = 2, s[i]='a'): partitionEnd = 8 Iteration (i = 3, s[i]='b'): partitionEnd = 8 Iteration (i = 4, s[i]='c'): partitionEnd = max(8, 7) = 8 Iteration (i = 5, s[i]='b'): partitionEnd = 8 Iteration (i = 6, s[i]='a'): partitionEnd = 8 Iteration (i = 7, s[i]='c'): partitionEnd = 8 Iteration (i = 8, s[i]='a'): i == partitionEnd (8) \u2192 Push size = 9 ans = [9] Reset partitionStart=9, partitionEnd=9 ------------------------------------------------------------ Iteration (i = 9, s[i]='d'): partitionEnd = max(9, 14) = 14 Iteration (i = 10, s[i]='e'): partitionEnd = max(14, 15) = 15 Iteration (i = 11, s[i]='f'): partitionEnd = 15 Iteration (i = 12, s[i]='e'): partitionEnd = 15 Iteration (i = 13, s[i]='g'): partitionEnd = 15 Iteration (i = 14, s[i]='d'): partitionEnd = 15 Iteration (i = 15, s[i]='e'): i == partitionEnd (15) \u2192 Push size = 7 ans = [9, 7] Reset partitionStart=16, partitionEnd=16 ------------------------------------------------------------ Iteration (i = 16, s[i]='h'): partitionEnd = max(16, 19) = 19 Iteration (i = 17, s[i]='i'): partitionEnd = max(19, 22) = 22 Iteration (i = 18, s[i]='j'): partitionEnd = max(22, 23) = 23 Iteration (i = 19, s[i]='h'): partitionEnd = 23 Iteration (i = 20, s[i]='k'): partitionEnd = 23 Iteration (i = 21, s[i]='l'): partitionEnd = 23 Iteration (i = 22, s[i]='i'): partitionEnd = 23 Iteration (i = 23, s[i]='j'): i == partitionEnd (23) \u2192 Push size = 8 ans = [9, 7, 8] ------------------------------------------------------------ Step 3: End Final ans = [9, 7, 8] <\/pre> <p><strong>Output:<\/strong> <code>[9, 7, 8]<\/code><\/p> <\/div>\n<\/div>\n\n\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\nvar partitionLabels = function(s) {\n    let last = {};\n    let ans = [];\n    for (let i = 0; i < s.length; i++) {\n        last[s[i]] = i;\n    }\n\n    let start = 0, end = 0;\n    for (let i = 0; i < s.length; i++) {\n        end = Math.max(end, last[s[i]]);\n        if (i === end) {\n            ans.push(end - start + 1);\n            start = i + 1;\n        }\n    }\n    return ans;\n};\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\ndef partition_labels(s: str):\n    last = [-1] * 26\n    for i, ch in enumerate(s):\n        last[ord(ch) - ord('a')] = i\n\n    ans = []\n    start = end = 0\n    for i, ch in enumerate(s):\n        end = max(end, last[ord(ch) - ord('a')])\n        if i == end:\n            ans.append(end - start + 1)\n            start = i + 1\n    return ans\n\nif __name__ == \"__main__\":\n    s = input().strip()\n    print(\" \".join(map(str, partition_labels(s))))\n      <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\nimport java.io.*;\nimport java.util.*;\npublic class Solution {\n    public static List<Integer> partitionLabels(String s) {\n        int[] last = new int[26];\n        Arrays.fill(last, -1);\n        for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;\n\n        List<Integer> ans = new ArrayList<>();\n        int start = 0, end = 0;\n        for (int i = 0; i < s.length(); i++) {\n            end = Math.max(end, last[s.charAt(i) - 'a']);\n            if (i == end) {\n                ans.add(end - start + 1);\n                start = i + 1;\n            }\n        }\n        return ans;\n    }\n    public static void main(String[] args) throws Exception {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        String s = br.readLine();\n        List<Integer> parts = partitionLabels(s);\n        System.out.println(String.join(\" \", parts.stream().map(String::valueOf).toArray(String[]::new)));\n    }\n}\n    <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n<!-- #include &lt;vector&gt; -->\n#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nvector<int> partitionLabels(const string &s) {\n    vector<int> last(26, -1);\n    for (int i = 0; i < (int)s.size(); ++i)\n        last[s[i] - 'a'] = i;\n    vector<int> ans;\n    int start = 0, end = 0;\n    for (int i = 0; i < (int)s.size(); ++i) {\n        end = max(end, last[s[i] - 'a']);\n        if (i == end) {\n            ans.push_back(end - start + 1);\n            start = i + 1;\n        }\n    }\n    return ans;\n}\nint main() {\n    string s;\n    getline(cin, s);\n    vector<int> res = partitionLabels(s);\n    for (size_t i = 0; i < res.size(); ++i) {\n        if (i) cout << \" \";\n        cout << res[i];\n    }\n    cout << \"\\n\";\n    return 0;\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main() {\n    char s[10005];\n    if (!fgets(s, sizeof(s), stdin)) return 0;\n    size_t n = strlen(s);\n    if (n > 0 && s[n-1] == '\\n') { s[n-1] = '\\0'; --n; }\n\n    int last[26];\n    for (int i = 0; i < 26; ++i) last[i] = -1;\n    for (int i = 0; i < (int)n; ++i) last[s[i] - 'a'] = i;\n\n    int *res = NULL;\n    int resCount = 0;\n    int start = 0, end = 0;\n    for (int i = 0; i < (int)n; ++i) {\n        if (last[s[i] - 'a'] > end) end = last[s[i] - 'a'];\n        if (i == end) {\n            int len = end - start + 1;\n            res = (int*)realloc(res, (resCount + 1) * sizeof(int));\n            res[resCount++] = len;\n            start = i + 1;\n        }\n    }\n    for (int i = 0; i < resCount; ++i) {\n        if (i) printf(\" \");\n        printf(\"%d\", res[i]);\n    }\n    printf(\"\\n\");\n    free(res);\n    return 0;\n}\n <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n      <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\nclass Solution {\n    public static IList<int> PartitionLabels(string s) {\n        int[] last = new int[26];\n        for (int i = 0; i < 26; i++) last[i] = -1;\n        for (int i = 0; i < s.Length; i++) last[s[i] - 'a'] = i;\n\n        List<int> ans = new List<int>();\n        int start = 0, end = 0;\n        for (int i = 0; i < s.Length; i++) {\n            end = Math.Max(end, last[s[i] - 'a']);\n            if (i == end) {\n                ans.Add(end - start + 1);\n                start = i + 1;\n            }\n        }\n        return ans;\n    }\n    static void Main() {\n        string s = Console.ReadLine();\n        var parts = PartitionLabels(s);\n        Console.WriteLine(string.Join(\" \", parts));\n    }\n}\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string &#8220;ababcc&#8221; can be partitioned into [&#8220;abab&#8221;, &#8220;cc&#8221;], but partitions such as [&#8220;aba&#8221;, &#8220;bcc&#8221;] or [&#8220;ab&#8221;, &#8220;ab&#8221;, &#8220;cc&#8221;] are invalid. Note<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":["post-10083","post","type-post","status-publish","format-standard","category-algorithms","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10083","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=10083"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10083\/revisions"}],"predecessor-version":[{"id":10084,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10083\/revisions\/10084"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=10083"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=10083"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=10083"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}