From 764983cbdb4acd8dd921b4be3c4b27061a5293a8 Mon Sep 17 00:00:00 2001 From: Viraj Jadhav Date: Sat, 18 Oct 2025 22:39:06 +0530 Subject: [PATCH] Create longest_substring_without_repeating_characters.cpp --- ...substring_without_repeating_characters.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 longest_substring_without_repeating_characters.cpp diff --git a/longest_substring_without_repeating_characters.cpp b/longest_substring_without_repeating_characters.cpp new file mode 100644 index 0000000..a5832bf --- /dev/null +++ b/longest_substring_without_repeating_characters.cpp @@ -0,0 +1,60 @@ +// Problem: Longest Substring Without Repeating Characters +// LeetCode: https://leetcode.com/problems/longest-substring-without-repeating-characters/ +// Author: DeveloperViraj (curated DSA set for Hacktoberfest 2025) +// Compile: g++ -std=c++17 01_longest_substring_without_repeating_characters.cpp -o 01_longest_substring +// Run: ./01_longest_substring +// +// Summary: +// Given a string, find the length of the longest substring without repeating characters. +// +// Approach (sliding window + last-seen index): +// Use two indices (windowStart and windowEnd) and a map of last-seen indices for characters. +// Expand the windowEnd and if the current character was seen inside the current window, +// move windowStart to lastSeenIndex + 1. Update the maximum window length as you go. +// +// Time Complexity: O(n) where n = length of string (each char visited at most twice). +// Space Complexity: O(min(n, charset)) for the hash map of last seen indices. + +#include +#include +#include +using namespace std; + +int lengthOfLongestUniqueSubstring(const string &s) { + unordered_map lastSeen; + int maxLength = 0; + int windowStart = 0; + + for (int windowEnd = 0; windowEnd < (int)s.size(); ++windowEnd) { + char currentChar = s[windowEnd]; + if (lastSeen.find(currentChar) != lastSeen.end()) { + // If this character appeared inside current window, move start + if (lastSeen[currentChar] >= windowStart) { + windowStart = lastSeen[currentChar] + 1; + } + } + lastSeen[currentChar] = windowEnd; + int windowLength = windowEnd - windowStart + 1; + if (windowLength > maxLength) maxLength = windowLength; + } + return maxLength; +} + +int main() { + cout << "Longest Substring Without Repeating Characters\n"; + cout << "Enter a single-line string and press Enter:\n"; + string input; + if (!getline(cin, input)) return 0; + + int result = lengthOfLongestUniqueSubstring(input); + cout << "Length: " << result << "\n"; + return 0; +} + +/* +Example: +Input: +abcabcbb +Output: +Length: 3 (substring "abc") +*/