Coding Interview — Multi-threading scenarios

Knowing multi-threading and how it works is good, but can we make use of it to solve some real-life problems? An interviewer may ask questions where he/she wants to know how would you tackle some scenarios and leverage multi-threading. Not to be forgotten that concurrency, synchronization and race conditions are to be kept in mind while answering such questions.

Here are some situations given to check your understanding and the ability to solve problems using multi-threading :

1. Given a large array of, say, a million numbers, sort it using multi-threading.

An Array

Sorting an array would involve both reads and writes at the same time. Putting a synchronization lock/monitor would defeat the idea of adding multiple threads.

2. Given a large array of lots and lots of integers, find their maximum using multi-threading.

Should different threads work on different sub-arrays and then combine their result at the end? Or there exists a better strategy?

3. Solve the above problems assuming data is read not from an array but a file.

Yeah, I/O gets tricky when multi-threading comes into play.

4. An uninitialized 2D array represents the pixels of an image. Two kinds of operations are done on each element — initialize the value after doing a calculation, and print its value. How would you do these two operations efficiently with multi-threading?

2D Array
2D Array
A 2D Array

The pixel can be printed only if its value has been calculated. To add more, is having two threads — to calculate and to print, a good idea? Or different threads should be assigned for different portions of the array, and each thread should perform both the operations? Should the pixels be processed in linear(left to right) or linear(top to bottom) or diagonal or random manner?

5. There are several file paths, and each file paths would receive CSV files of specific format, with specific name. How would you continuously watch these file paths, and generate an alert as soon as any file is received?

The process should continuously monitor these locations, all together. And check if a new file has been put. What if the same file location, receives another file to replace the older one? What if the newer file does not replace the older, but creates a copy and appends v1/v2/… at the end?

These are a few of the problems that come to my mind when I think of multi-threading as an approach. Please feel free to drop comments/feedback/suggest more problems.

Software | Algorithms | Astronomy