Skip to content
CodeKruPro

Remove extra spaces from a sentence

Coding problemEasy

Given a string s, return it with every run of spaces replaced by a single space, and with no spaces at the start or end.

Interviewers ask for this without ready-made trim, split or replace helpers, so walk the characters yourself. A string of only spaces gives an empty string.

Examples

Example 1
Input: s = " hello world "
Output: "hello world"
Example 2
Input: s = "one two three"
Output: "one two three"
Example 3
Input: s = " "
Output: ""

Constraints

  • The length of s is between 0 and 100,000
  • s holds printable ASCII characters only; only the space character counts as a space

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in