Skip to content

Conversation

@dchou1618
Copy link
Owner

@dchou1618 dchou1618 commented Jan 4, 2026

User description

longest substr


PR Type

Enhancement, Tests


Description

  • Implement sliding window algorithms for longest substring and maximum subarray

  • Add lengthOfLongestSubstringTwoDistinct function with OrderedDict tracking

  • Add maximumUniqueSubarray function for finding max sum of unique elements

  • Comprehensive test suite with 30+ test cases covering edge cases and validation


Diagram Walkthrough

flowchart LR
  A["Sliding Window Algorithms"] --> B["lengthOfLongestSubstringTwoDistinct"]
  A --> C["maximumUniqueSubarray"]
  B --> D["OrderedDict tracking"]
  C --> E["Hash map with index tracking"]
  D --> F["Test Suite"]
  E --> F
  F --> G["30+ parametrized tests"]
  F --> H["Edge cases & validation"]
Loading

File Walkthrough

Relevant files
Enhancement
longestUnique.py
Sliding window algorithms for substring and subarray problems

Algorithms/slidingWindow/longestUnique.py

  • Implement lengthOfLongestSubstringTwoDistinct using OrderedDict to
    track at most 2 distinct characters
  • Implement maximumUniqueSubarray to find maximum sum of subarray with
    all unique elements
  • Define SlidingWindowParam Pydantic model for input validation with
    minimum length constraint
  • Both functions use sliding window technique with efficient pointer
    management
+35/-0   
Tests
test_longest_substring.py
Comprehensive test suite for sliding window algorithms     

tests/test_longest_substring.py

  • Add 7 parametrized basic correctness tests for
    lengthOfLongestSubstringTwoDistinct
  • Add 7 parametrized basic correctness tests for maximumUniqueSubarray
  • Add 8 regression and tricky case tests including eviction order and
    multiple duplicates
  • Add 6 edge case tests covering all same characters, large values, and
    alternating patterns
  • Add Pydantic validation tests for empty string rejection and type
    checking
  • Add 8 invariant-style tests ensuring results respect bounds
    constraints
+164/-0 

@dchou1618 dchou1618 self-assigned this Jan 4, 2026
@dchou1618 dchou1618 marked this pull request as ready for review January 4, 2026 20:36
@qodo-code-review
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
Algorithmic complexity

Description: maximumUniqueSubarray performs sum(nums[start:(last_idx+1)]) inside the main loop, which
can degrade to O(n^2) time on adversarial inputs with frequent duplicates, creating a
realistic algorithmic-complexity (DoS) risk if nums is user-controlled and large.
longestUnique.py [23-33]

Referred Code
def maximumUniqueSubarray(nums: List[int]) -> int:
    last_seen = dict()
    start, curr_sum, max_sum = 0, 0, 0
    for end in range(len(nums)):
        if nums[end] in last_seen:
            last_idx = last_seen[nums[end]] 
            if last_idx >= start:
                curr_sum -= sum(nums[start:(last_idx+1)])
                start = last_idx + 1
        curr_sum += nums[end]
        max_sum = max(max_sum, curr_sum)
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Incorrect input type: lengthOfLongestSubstringTwoDistinct will raise runtime errors if called according to its
signature (passing a SlidingWindowParam), because it performs string indexing and len()
operations on the model instead of its s field.

Referred Code
def lengthOfLongestSubstringTwoDistinct(s: SlidingWindowParam) -> int:
    seen = OrderedDict()
    start = 0
    longest = 0
    for end in range(len(s)):
        if s[end] in seen:
            seen.move_to_end(s[end])
        seen[s[end]] = end
        if len(seen) > 2:
            _, idx = seen.popitem(last=False)
            start = idx+1
        longest = max(longest, end-start+1)
    return longest

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status:
Misleading type hint: The function lengthOfLongestSubstringTwoDistinct type-annotates s as SlidingWindowParam
but uses it like a string, which is misleading and harms self-documentation.

Referred Code
def lengthOfLongestSubstringTwoDistinct(s: SlidingWindowParam) -> int:
    seen = OrderedDict()
    start = 0
    longest = 0
    for end in range(len(s)):
        if s[end] in seen:
            seen.move_to_end(s[end])
        seen[s[end]] = end

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Missing nums validation: maximumUniqueSubarray accepts nums without validating type/contents (e.g., non-list inputs
or non-integer elements), which may be acceptable for an algorithms module but is
unverified from the diff alone.

Referred Code
def maximumUniqueSubarray(nums: List[int]) -> int:
    last_seen = dict()
    start, curr_sum, max_sum = 0, 0, 0
    for end in range(len(nums)):
        if nums[end] in last_seen:
            last_idx = last_seen[nums[end]] 
            if last_idx >= start:
                curr_sum -= sum(nums[start:(last_idx+1)])
                start = last_idx + 1
        curr_sum += nums[end]
        max_sum = max(max_sum, curr_sum)
        last_seen[nums[end]] = end
    return max_sum

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Use string parameter type

Change the signature of lengthOfLongestSubstringTwoDistinct to accept a str
parameter instead of SlidingWindowParam to match its usage in the tests.

Algorithms/slidingWindow/longestUnique.py [9]

-def lengthOfLongestSubstringTwoDistinct(s: SlidingWindowParam) -> int:
+def lengthOfLongestSubstringTwoDistinct(s: str) -> int:
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical inconsistency between the function's type hint (SlidingWindowParam) and its actual usage with a str in tests, proposing a fix that makes the code correct and logical.

High
Optimize window sum eviction

In maximumUniqueSubarray, replace the inefficient sum(nums[start:(last_idx+1)])
with a loop to improve performance from O(N^2) to O(N).

Algorithms/slidingWindow/longestUnique.py [30]

-curr_sum -= sum(nums[start:(last_idx+1)])
+for i in range(start, last_idx+1):
+    curr_sum -= nums[i]
+start = last_idx + 1
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a significant performance bottleneck (sum on a slice) that results in O(N^2) complexity and proposes a fix that improves it to O(N).

Medium
Possible issue
Avoid duplicate test names

Rename the test function test_basic_cases at line 37 to a unique name to prevent
it from overwriting the other test with the same name.

tests/test_longest_substring.py [37]

-def test_basic_cases(nums, expected):
+def test_maximum_unique_subarray_basic_cases(nums, expected):
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that two test functions have the same name, which would cause pytest to run only the second one, leaving the first untested.

Medium
  • More

@dchou1618 dchou1618 merged commit 9fcfd74 into master Jan 4, 2026
3 checks passed
@dchou1618 dchou1618 deleted the feat/hash-table-3 branch January 4, 2026 21:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants