bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 2405. Optimal Partition of String

2405. Optimal Partition of String

Leetcode Solutions

Greedy Approach for Partitioning String into Unique Substrings

  1. Initialize an array lastSeen of size 26 to -1 to keep track of the most recent position of each character.
  2. Initialize count to 1 as we start with the first substring.
  3. Initialize substringStart to 0 to mark the beginning of the current substring.
  4. Iterate over the string s and for each character at index i:
    • Check if the character has been seen in the current substring by comparing lastSeen[s[i] - 'a'] with substringStart.
    • If it has been seen, increment count, start a new substring, and update substringStart to i.
    • Update lastSeen[s[i] - 'a'] to i.
  5. Return count.
UML Thumbnail

HashSet Approach for Partitioning String into Unique Substrings

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...