Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

Longest Substring Without Repeating Characters

/*
    Javascript Solution - With Better Performance
    Methods used in this algorithm are:
    1. Two Pointer Technique
    2. Sliding Window Technique
    3. Hash Map

    Time complexity: O(N)
    Space complexity: O(N),
    If the string does not contain repeated characters, 
    then the hash map will contain N characters.
*/

const s = "sdtvtsgh"

const lengthOfLongestSubstring = function(s) {
    let max_length = 0
    let map = {}
    let l = 0

    for (let r = 0; r < s.length; r++) {
        if (map.hasOwnProperty(s[r])) {
            const collision_index = map[s[r]]

            if (collision_index >= l) {
                l = collision_index + 1
            }

            delete map[s[collision_index]]
        }

        if (!map.hasOwnProperty(s[r])) {
            map[s[r]] = r
        }

        if (max_length < (r + 1) - l) {
            max_length = (r + 1) - l
        }

        console.log(map, ':   (', r + 1, '-', l, ')')
    }

    return max_length
}


console.log(lengthOfLongestSubstring(s))

// [Log]:
{ s: 0 } :   ( 1 - 0 )
{ s: 0, d: 1 } :   ( 2 - 0 )
{ s: 0, d: 1, t: 2 } :   ( 3 - 0 )
{ s: 0, d: 1, t: 2, v: 3 } :   ( 4 - 0 )
{ s: 0, d: 1, v: 3, t: 4 } :   ( 5 - 3 )
{ d: 1, v: 3, t: 4, s: 5 } :   ( 6 - 3 )
{ d: 1, v: 3, t: 4, s: 5, g: 6 } :   ( 7 - 3 )
{ d: 1, v: 3, t: 4, s: 5, g: 6, h: 7 } :   ( 8 - 3 )

max_length = 5
 
PREVIOUS NEXT
Tagged: #Longest #Substring #Without #Repeating #Characters
ADD COMMENT
Topic
Name
6+2 =