Length of longest unique substring



    pavan koka

    This function takes as its only parameter a string and returns the length of the longest substring of that string.

    First, the function creates an "empty" mapping object that will store the results of the function. The mapping object will be indexed by string position and will keep track of whether or not the string at that position has been marked as being in the result set.

    Next, the function loops through the string and sets the mapping object entries for each character to true. This will mark the string as being part of the result set.

    Next, the function determines the length of the longest substring and returns that value.

    var lengthOfLongestSubstring = function(s) {
      if(!s.length) return 0;
      let result = 1;
      const mapping = {};
      let l=0, r=0; 
      mapping[s[0]] = true;
      while(r < s.length) {
        if(l == r) {
        if(!mapping[s[l]]) {
          mapping[s[l]] = true;
        if(!mapping[s[r]]) {
          mapping[s[r]] = true;
          if(r-l+1 > result) {
            result = r-l+1
        } else {
          delete mapping[s[l]];
      return result
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.