Remove White Spaces

Coding Skill Exercise #23

Remove White Spaces

Write a method to remove white spaces from a given string. The string may contain tabs or spaces.

Knowledge Gap Finder

If you are unable to code the solution, answer the following questions and reply to this email to get customized lesson.

Was the problem statement clear to you when you read it? What did you think of doing first? Were you reminded of a construct in general or a general structure of solution that you thought would be useful? Have you previously seen problems that resemble this one? Did you feel stuck at any point while working on this problem? What did you choose as your test case? Do you think you’ve covered all possible scenarios with your tests? What program design techniques did you apply to solve this problem? Are there any constructs of the programming language that you find difficult or confusing to use? What issues make programming constructs difficult to use? For example, the keyword used, the syntax, the examples, the documentation for the construct, etc.

Feel free to forward this email to your friends so they can subscribe here. https://codingskill.biz

title: Remove Whitespaces excerpt: Solution for a common string interview question. tags: two-pointers-moving-in-same-direction read-and-write-pointers two-pointers-left-to-right-scan

The string is modified by copying only non white spaces characters. Read pointer skips any white space or tab characters, it is copied to the string to the location pointed by write pointer. The substring formed from the index 0 to the write index gives the string without white spaces.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def remove_white_spaces(s)
  if (!s || s.size == 0)
    return
  end
  
  read = 0
  write = 0
  
  while read < s.size
    if s[read] != ' ' && s[read] != '\t'
      s[write] = s[read]
      write += 1
    end
    read += 1
  end
  
  s[0, write]
end

s = '     All greek  to    me.    '

p remove_white_spaces(s)

Building Blocks

  • Read and Write Pointers
  • Two Pointers Moving in Same Direction

The read and write pointers are initialized to 0 and move from left to right in the input string.