Fork me on GitHub

Project Notes

#500 simplifyRoute

Using ruby to simplify a hiking route: cassidoo’s interview question of the week (2026-11-30).

Notes

The interview question of the week (2026-11-30):

A hiking route is a list of “N”, “S”, “E”, and “W” steps. Whenever two adjacent steps go in opposite directions, they cancel each other out. Repeatedly cancel such pairs until none remain, then return the simplified route in order.

Examples:

simplifyRoute(["N", "E", "W", "S", "W"])
> ["W"] // E/W cancel, then N/S cancel

simplifyRoute(["N", "N", "S", "E", "W", "W"])
> ["N", "W"]

simplifyRoute(["N", "E", "W", "S"])
> []

simplifyRoute(["N", "E", "S", "W"])
> ["N", "E", "S", "W"]

Thinking about the Problem

We need to eliminate redundant movements such as "E", "W". One could approach this as an array manipulating problem, but it perhaps may be easier to handle it as a string substitution

Initial Solution

Here’s a first go:

  • convert the array to a string
  • substitute redundant movements
  • repeat until no further substitutions found
def simplifyRoute(directions)
  result = directions.join('')
  loop do
    previous = result
    result = previous.gsub(/NS|SN|EW|WE/, '')
    break if result == previous
  end
  result.split('')
end

It’s working with the given examples:

$ ./challenge.rb
Usage: ruby ./challenge.rb <csv-directions>
$ ./challenge.rb "N, E, W, S, W"
directions: ["N", "E", "W", "S", "W"]
Result:
["W"]
$ ./challenge.rb "N, N, S, E, W, W"
directions: ["N", "N", "S", "E", "W", "W"]
Result:
["N", "W"]
$ ./challenge.rb "N, E, W, S"
directions: ["N", "E", "W", "S"]
Result:
[]
$ ./challenge.rb "N, E, S, W"
directions: ["N", "E", "S", "W"]
Result:
["N", "E", "S", "W"]

Simplifying the Code

The code is a bit cumbersome. We can eliminate manually tracking previous/next values by switching from String#gsub to String#gsub!, since it tells us whether replacements were made:

def simplifyRoute(directions)
  result = directions.join('')
  loop { break unless result.gsub!(/NS|SN|EW|WE/, '') }
  result.split('')
end

A Better Approach?

This approach is pretty good for simple cases. But for extended directions prone to significant simplification, the performance will suffer from the looping and repeated string modification.

So is there a one-pass approach that is still able to deal with repeated cancellation? It seems like it:

  • process the input array step by step
  • if the next step cancels the previous, then just remove the previous step
  • else add the new step
def simplifyRoute(directions)
  reverse = { 'N' => 'S', 'S' => 'N', 'E' => 'W', 'W' => 'E' }
  directions.each_with_object([]) do |step, simplified|
    reverse[step] == simplified.last ? simplified.pop : simplified.push(step)
  end
end

Well that works with all the examples:

$ ./challenge.rb
Usage: ruby ./challenge.rb <csv-directions> (v1|v2[default])
$ ./challenge.rb "N, E, W, S, W" v1
directions: ["N", "E", "W", "S", "W"]
Result:
["W"]
$ ./challenge.rb "N, E, W, S, W" v2
directions: ["N", "E", "W", "S", "W"]
Result:
["W"]
...
etc

But does it perform any better? I’ve added a benchmark.rb test:

$ ./benchmark.rb
ruby 3.4.8 (2025-12-17 revision 995b59f666) +PRISM [arm64-darwin24]
Warming up --------------------------------------
 gsub-based - short_journey   121.975k i/100ms
single-pass - short_journey   138.388k i/100ms
  gsub-based - long_journey     1.713k i/100ms
 single-pass - long_journey     3.152k i/100ms
Calculating -------------------------------------
 gsub-based - short_journey      1.246M (± 0.9%) i/s  (802.30 ns/i) -      6.343M in   5.088760s
single-pass - short_journey      1.381M (± 0.6%) i/s  (724.24 ns/i) -      6.919M in   5.011333s
  gsub-based - long_journey     17.227k (± 0.4%) i/s   (58.05 μs/i) -     87.363k in   5.071389s
 single-pass - long_journey     31.369k (± 0.4%) i/s   (31.88 μs/i) -    157.600k in   5.024129s

Comparison:
single-pass - short_journey:  1380750.4 i/s
 gsub-based - short_journey:  1246413.7 i/s - 1.11x  slower
 single-pass - long_journey:    31368.6 i/s - 44.02x  slower
  gsub-based - long_journey:    17226.6 i/s - 80.15x  slower

So yes, the single-pass approach is always better, especially with long journeys where it can be twice as fast.

Tests

I’ve setup some validation in test_challenge.rb:

$ ./test_challenge.rb
Run options: --seed 56696

# Running:

........

Finished in 0.000329s, 24316.1094 runs/s, 24316.1094 assertions/s.

8 runs, 8 assertions, 0 failures, 0 errors, 0 skips

Final Code

Final code is in challenge.rb:

#!/usr/bin/env ruby

def simplifyRouteV1(directions)
  result = directions.join('')
  loop { break unless result.gsub!(/NS|SN|EW|WE/, '') }
  result.split('')
end

def simplifyRoute(directions)
  reverse = { 'N' => 'S', 'S' => 'N', 'E' => 'W', 'W' => 'E' }
  directions.each_with_object([]) do |step, simplified|
    reverse[step] == simplified.last ? simplified.pop : simplified.push(step)
  end
end

if __FILE__ == $PROGRAM_NAME
  (warn "Usage: ruby #{$0} <csv-directions> (v1|v2[default])"; exit) unless ARGV.length == 1 || ARGV.length == 2
  directions = ARGV[0].split(',').map(&:strip)
  warn "directions: #{directions.inspect}"
  case ARGV[1]
  when 'v1'
    result = simplifyRouteV1(directions)
  else
    result = simplifyRoute(directions)
  end
  warn 'Result:'
  puts result.inspect
end

Credits and References

About LCK#500
Rubycassidoo

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

Project Source on GitHub Return to the LittleCodingKata Catalog
About LittleCodingKata

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.

Follow the Blog follow projects and notes as they are published in your favourite feed reader