Solving Canva’s Technical Challenge With a Single Reduce Function

Refactoring JavaScript: Collection Pipelines (Example)

Michael Timbs
The Startup

--

This is part of a series called “Refactoring Javascript: Collection Pipelines.” You can read the introduction here.

In a previous article, I gave an introduction to the power of reduce(), however, I didn’t really highlight it’s potential with a real world example.

In this article we will solve the Canva technical challenge using a single reduce function.

Note: In the event that Canva is still using this question to screen candidates, be aware that they use HackerRank to check for plagiarism, don’t try to submit this answer.

The Challenge

The task is to write an algorithm that takes two parameters. The first parameter is an array of integers (a), the second is an integer (k). You are asked to return the length of the longest subarray within a, such that the sum of its elements is less than or equal to k.

A subarray of an n-element array is an array composed from a contiguous block of the original array’s elements. For example, if a = [1,2,3], then the subarrays are [1],[2],[3],[1,2] ,[2,3] , and [1,2,3]. Something like [1,3] would not be a subarray as it’s not a contiguous subsection…

--

--

Michael Timbs
The Startup

Full-stack developer. In love with Typescript and Serverless