Length of longest non-repeating substring challenge using sliding window“Longest Palindromic Substring”...
Explain the objections to these measures against human trafficking
How to acknowledge an embarrassing job interview, now that I work directly with the interviewer?
Is it a fallacy if someone claims they need an explanation for every word of your argument to the point where they don't understand common terms?
Why are the books in the Game of Thrones citadel library shelved spine inwards?
Every character has a name
Can I become debt free or should I file for bankruptcy? How do I manage my debt and finances?
Cryptic with missing capitals
Does Windows 10's telemetry include sending *.doc files if Word crashed?
Why is working on the same position for more than 15 years not a red flag?
Blindfold battle as a gladiatorial spectacle - what are the tactics and communication methods?
Eww, those bytes are gross
My cat mixes up the floors in my building. How can I help him?
Word or phrase for showing great skill at something without formal training in it
How to deal with an incendiary email that was recalled
Why is "points exist" not an axiom in geometry?
Indirectly access environment variable
Why zero tolerance on nudity in space?
What is this metal M-shaped device for?
Is there any differences between "Gucken" and "Schauen"?
How can I install sudo without using su?
Can a person refuse a presidential pardon?
What makes the Forgotten Realms "forgotten"?
Parsing a string of key-value pairs as a dictionary
If I delete my router's history can my ISP still provide it to my parents?
Length of longest non-repeating substring challenge using sliding window
“Longest Palindromic Substring” challenge solution is inefficientImproving efficiency for finding longest contiguous non-decreasing substringLongest Palindromic SubstringMinimum window substringLongest repeating and non-overlapping substringSliding window of entire length of the fileGeneric sliding windowSliding window to solve “longest substring, no repeating chars”“Longest Substring Without Repeating Characters” in PythonLongest Palindromic Substring challenge
$begingroup$
I am working on Leetcode challenge #3 (https://leetcode.com/problems/longest-substring-without-repeating-characters/)
Here is my solution using sliding window and a dictionary. I specifically added start = seen[s[i]]+1 to skip ahead. I am still told I am far slower than most people (for example, given abcdefgdabc, I am skipping abc when I see the second d. I thought this would save ton of time, but apparently this algorithm has a poor run time.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
seen = {}
start = 0
max_size = 0
# check whether left pointer has reached the end yet
while start < len(s):
size = 0
for i in range(start, len(s)):
if s[i] in seen:
start = seen[s[i]]+1
seen = {}
break
else:
seen[s[i]] = i
size += 1
max_size = max(size, max_size)
return max_size
UPDATE
i = 0
j = 0
seen = {}
max_length = 0
while j < len(s):
if s[j] not in seen:
seen[s[j]] = j
j += 1
max_length = max(max_length, j-i)
else:
i = j = seen[s[j]] + 1
seen = {}
return max_length
python algorithm
$endgroup$
add a comment |
$begingroup$
I am working on Leetcode challenge #3 (https://leetcode.com/problems/longest-substring-without-repeating-characters/)
Here is my solution using sliding window and a dictionary. I specifically added start = seen[s[i]]+1 to skip ahead. I am still told I am far slower than most people (for example, given abcdefgdabc, I am skipping abc when I see the second d. I thought this would save ton of time, but apparently this algorithm has a poor run time.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
seen = {}
start = 0
max_size = 0
# check whether left pointer has reached the end yet
while start < len(s):
size = 0
for i in range(start, len(s)):
if s[i] in seen:
start = seen[s[i]]+1
seen = {}
break
else:
seen[s[i]] = i
size += 1
max_size = max(size, max_size)
return max_size
UPDATE
i = 0
j = 0
seen = {}
max_length = 0
while j < len(s):
if s[j] not in seen:
seen[s[j]] = j
j += 1
max_length = max(max_length, j-i)
else:
i = j = seen[s[j]] + 1
seen = {}
return max_length
python algorithm
$endgroup$
add a comment |
$begingroup$
I am working on Leetcode challenge #3 (https://leetcode.com/problems/longest-substring-without-repeating-characters/)
Here is my solution using sliding window and a dictionary. I specifically added start = seen[s[i]]+1 to skip ahead. I am still told I am far slower than most people (for example, given abcdefgdabc, I am skipping abc when I see the second d. I thought this would save ton of time, but apparently this algorithm has a poor run time.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
seen = {}
start = 0
max_size = 0
# check whether left pointer has reached the end yet
while start < len(s):
size = 0
for i in range(start, len(s)):
if s[i] in seen:
start = seen[s[i]]+1
seen = {}
break
else:
seen[s[i]] = i
size += 1
max_size = max(size, max_size)
return max_size
UPDATE
i = 0
j = 0
seen = {}
max_length = 0
while j < len(s):
if s[j] not in seen:
seen[s[j]] = j
j += 1
max_length = max(max_length, j-i)
else:
i = j = seen[s[j]] + 1
seen = {}
return max_length
python algorithm
$endgroup$
I am working on Leetcode challenge #3 (https://leetcode.com/problems/longest-substring-without-repeating-characters/)
Here is my solution using sliding window and a dictionary. I specifically added start = seen[s[i]]+1 to skip ahead. I am still told I am far slower than most people (for example, given abcdefgdabc, I am skipping abc when I see the second d. I thought this would save ton of time, but apparently this algorithm has a poor run time.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
seen = {}
start = 0
max_size = 0
# check whether left pointer has reached the end yet
while start < len(s):
size = 0
for i in range(start, len(s)):
if s[i] in seen:
start = seen[s[i]]+1
seen = {}
break
else:
seen[s[i]] = i
size += 1
max_size = max(size, max_size)
return max_size
UPDATE
i = 0
j = 0
seen = {}
max_length = 0
while j < len(s):
if s[j] not in seen:
seen[s[j]] = j
j += 1
max_length = max(max_length, j-i)
else:
i = j = seen[s[j]] + 1
seen = {}
return max_length
python algorithm
python algorithm
edited 2 days ago
CppLearner
asked Feb 25 at 1:33
CppLearnerCppLearner
264210
264210
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
In this loop, while start < len(s):, the string s is not changing, so the length of the string is not going to change either. Yet, for each iteration, you will evaluate len(s) in order to evaluate the loop condition. len(s) is undoubtably a fast operation, but you should still cache the result to avoid the function call every iteration.
limit = len(s)
while start < limit:
# ...
The loop for i in range(start, len(s)):, you are again calling len(s) for each iteration (of the outer loop). You could replace this with for i in range(start, limit):, but we will still have a different issue...
You are (mostly) not using i inside the loop; you are using s[i]. And you look up the character s[i] in 3 different places inside the loop. Instead of looping over the indices, and looking up the character at the index, you should directly loop over the characters of the string.
for ch in s[start:]:
# ...
Except for that pesky seen[...] = i statement. You still want the index. The enumerate() function can be used to count as you are looping:
for i, ch in enumerate(s[start:], start):
if ch in seen:
start = seen[ch]+1
seen = {}
break
else:
seen[ch] = i
size += 1
Hint
When scanning the string abcdefgdhijklmn, after encountering the second d, you reset to the character after the first d, and continue your scan. But ...
Do you have to? Aren’t all the characters between the first d and the second d unique? Is there any way you could preserve that information, and continue on, without needing to restart with the e? Maybe you don’t need nested loops!
$endgroup$
$begingroup$
Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better.
$endgroup$
– CppLearner
2 days ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214211%2flength-of-longest-non-repeating-substring-challenge-using-sliding-window%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
In this loop, while start < len(s):, the string s is not changing, so the length of the string is not going to change either. Yet, for each iteration, you will evaluate len(s) in order to evaluate the loop condition. len(s) is undoubtably a fast operation, but you should still cache the result to avoid the function call every iteration.
limit = len(s)
while start < limit:
# ...
The loop for i in range(start, len(s)):, you are again calling len(s) for each iteration (of the outer loop). You could replace this with for i in range(start, limit):, but we will still have a different issue...
You are (mostly) not using i inside the loop; you are using s[i]. And you look up the character s[i] in 3 different places inside the loop. Instead of looping over the indices, and looking up the character at the index, you should directly loop over the characters of the string.
for ch in s[start:]:
# ...
Except for that pesky seen[...] = i statement. You still want the index. The enumerate() function can be used to count as you are looping:
for i, ch in enumerate(s[start:], start):
if ch in seen:
start = seen[ch]+1
seen = {}
break
else:
seen[ch] = i
size += 1
Hint
When scanning the string abcdefgdhijklmn, after encountering the second d, you reset to the character after the first d, and continue your scan. But ...
Do you have to? Aren’t all the characters between the first d and the second d unique? Is there any way you could preserve that information, and continue on, without needing to restart with the e? Maybe you don’t need nested loops!
$endgroup$
$begingroup$
Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better.
$endgroup$
– CppLearner
2 days ago
add a comment |
$begingroup$
In this loop, while start < len(s):, the string s is not changing, so the length of the string is not going to change either. Yet, for each iteration, you will evaluate len(s) in order to evaluate the loop condition. len(s) is undoubtably a fast operation, but you should still cache the result to avoid the function call every iteration.
limit = len(s)
while start < limit:
# ...
The loop for i in range(start, len(s)):, you are again calling len(s) for each iteration (of the outer loop). You could replace this with for i in range(start, limit):, but we will still have a different issue...
You are (mostly) not using i inside the loop; you are using s[i]. And you look up the character s[i] in 3 different places inside the loop. Instead of looping over the indices, and looking up the character at the index, you should directly loop over the characters of the string.
for ch in s[start:]:
# ...
Except for that pesky seen[...] = i statement. You still want the index. The enumerate() function can be used to count as you are looping:
for i, ch in enumerate(s[start:], start):
if ch in seen:
start = seen[ch]+1
seen = {}
break
else:
seen[ch] = i
size += 1
Hint
When scanning the string abcdefgdhijklmn, after encountering the second d, you reset to the character after the first d, and continue your scan. But ...
Do you have to? Aren’t all the characters between the first d and the second d unique? Is there any way you could preserve that information, and continue on, without needing to restart with the e? Maybe you don’t need nested loops!
$endgroup$
$begingroup$
Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better.
$endgroup$
– CppLearner
2 days ago
add a comment |
$begingroup$
In this loop, while start < len(s):, the string s is not changing, so the length of the string is not going to change either. Yet, for each iteration, you will evaluate len(s) in order to evaluate the loop condition. len(s) is undoubtably a fast operation, but you should still cache the result to avoid the function call every iteration.
limit = len(s)
while start < limit:
# ...
The loop for i in range(start, len(s)):, you are again calling len(s) for each iteration (of the outer loop). You could replace this with for i in range(start, limit):, but we will still have a different issue...
You are (mostly) not using i inside the loop; you are using s[i]. And you look up the character s[i] in 3 different places inside the loop. Instead of looping over the indices, and looking up the character at the index, you should directly loop over the characters of the string.
for ch in s[start:]:
# ...
Except for that pesky seen[...] = i statement. You still want the index. The enumerate() function can be used to count as you are looping:
for i, ch in enumerate(s[start:], start):
if ch in seen:
start = seen[ch]+1
seen = {}
break
else:
seen[ch] = i
size += 1
Hint
When scanning the string abcdefgdhijklmn, after encountering the second d, you reset to the character after the first d, and continue your scan. But ...
Do you have to? Aren’t all the characters between the first d and the second d unique? Is there any way you could preserve that information, and continue on, without needing to restart with the e? Maybe you don’t need nested loops!
$endgroup$
In this loop, while start < len(s):, the string s is not changing, so the length of the string is not going to change either. Yet, for each iteration, you will evaluate len(s) in order to evaluate the loop condition. len(s) is undoubtably a fast operation, but you should still cache the result to avoid the function call every iteration.
limit = len(s)
while start < limit:
# ...
The loop for i in range(start, len(s)):, you are again calling len(s) for each iteration (of the outer loop). You could replace this with for i in range(start, limit):, but we will still have a different issue...
You are (mostly) not using i inside the loop; you are using s[i]. And you look up the character s[i] in 3 different places inside the loop. Instead of looping over the indices, and looking up the character at the index, you should directly loop over the characters of the string.
for ch in s[start:]:
# ...
Except for that pesky seen[...] = i statement. You still want the index. The enumerate() function can be used to count as you are looping:
for i, ch in enumerate(s[start:], start):
if ch in seen:
start = seen[ch]+1
seen = {}
break
else:
seen[ch] = i
size += 1
Hint
When scanning the string abcdefgdhijklmn, after encountering the second d, you reset to the character after the first d, and continue your scan. But ...
Do you have to? Aren’t all the characters between the first d and the second d unique? Is there any way you could preserve that information, and continue on, without needing to restart with the e? Maybe you don’t need nested loops!
edited Feb 26 at 17:19
answered Feb 25 at 6:07
AJNeufeldAJNeufeld
5,5291420
5,5291420
$begingroup$
Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better.
$endgroup$
– CppLearner
2 days ago
add a comment |
$begingroup$
Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better.
$endgroup$
– CppLearner
2 days ago
$begingroup$
Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better.
$endgroup$
– CppLearner
2 days ago
$begingroup$
Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better.
$endgroup$
– CppLearner
2 days ago
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214211%2flength-of-longest-non-repeating-substring-challenge-using-sliding-window%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown