Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 19

Extract a Substring by Index

Medium

15 minute session

Summary

Return a substring from a string given start and end indices (inclusive), handling negative and out-of-range indices gracefully.

Problem statement

Implement extract_substring(s, start, end) that returns the substring of s starting at index start and ending at index end (inclusive). Indices are 0-based. Both start and end may be negative (meaning count from the end, like Python indexing). If an index is out of range it should be clamped to the valid bounds of the string. If after clamping start > end, return the empty string. Do not use print; return the substring.

Task

Write a function that extracts a substring from index start to end (inclusive), supporting negative indices and clamping out-of-range values.

Examples

Basic example

Input

extract_substring('hello', 1, 3)

Output

ell

Explanation

Characters at indices 1..3 are 'e','l','l' -> 'ell'.

Input format

A string s and two integers start and end, passed as arguments to extract_substring(s, start, end).

Output format

A string: the substring from start to end inclusive (or empty string if start > end after clamping).

Constraints

- Do not use external libraries. - s length can be 0..1000. - start and end are integers and may be negative or outside string bounds. - Must handle negative indices by counting from the end (like Python negatives).

Samples

Sample input 0

extract_substring('python', -3, -1)

Sample output 0

hon

Explanation 0

Indices -3..-1 correspond to 'h','o','n'.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 AM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.