Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
String or Array Manipulation Function
00:00
5 left

String or Array Manipulation Function

MediumPython

Problem

Medscape Search may receive queries containing repeated terms or characters. Given a search query string, return its longest contiguous substring that contains no repeated characters.

Use a sliding-window approach that scans the query once. If multiple longest substrings exist, return the one that appears first. Characters are compared exactly, so uppercase letters, lowercase letters, spaces, and punctuation are distinct.

Formal Specification

Implement longest_unique_segment(query), where query is a string. Return a string containing the longest contiguous portion of query in which every character appears at most once. Return an empty string when query is empty. The input must not be modified.

Example 1:

Input: query = "medscape"
Output: "medscape"

Every character appears once, so the complete query is valid.

Example 2:

Input: query = "abcabcbb"
Output: "abc"

The longest valid segments have length three. The first one, "abc", is returned.

Example 3:

Input: query = "pwwkew"
Output: "wke"

"wke" is the longest contiguous substring with no repeated characters.

Constraints

  • 0 <= len(query) <= 100,000
  • query contains printable ASCII characters
  • The input string must not be modified
  • Ties are resolved by returning the earliest longest segment

Function Signature

def longest_unique_segment(query):
Interviewer

Your question is String or Array Manipulation Function. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.