DEV Community

Cover image for A common coding interview question
elisabethgross for Coderbyte

Posted on • Updated on

A common coding interview question

Hey everyone! Welcome back to Code Review, a series of interview challenges released weekly that are completely free for the community. This week we’ll be working on a common, relatively straightforward question that I personally have been asked multiple times in interviews. I chose this challenge because there are multiple ways to approach the problem, each with various time and space trade-offs.

The Challenge:

Write a function, FindIntersection, that reads an array of strings which will contain two elements: the first element will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers (also sorted). Your goal is to return a string of numbers that occur in both elements of the input array in sorted order. If there is no intersection, return the string "false".

For example: if the input array is ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] the output string should be "1, 4, 13" because those numbers appear in both strings. The array given will not be empty, and each string inside the array will be of numbers sorted in ascending order and may contain negative numbers.

The Brute Force Solution:

A brute-force solution is to loop over the numbers of the first string, and for each number in the first string, loop over all numbers of the other string, looking for a match. If a match is found, concat that value to a result string.

function FindIntersection (strArr) {
  const inBothStrings = []
  const arr1 = strArr[0].split(', ')
  const arr2 = strArr[1].split(', ')
  arr1.forEach(elementArr1 => {
    const numArr1 = parseInt(elementArr1)
    arr2.forEach(elementArr2 => {
      const numArr2 = parseInt(elementArr2)
      if (numArr1 === numArr2) {
        inBothStrings.push(numArr1)
      }
    })
  })
  return inBothStrings.join(',')
}

Although this will work, it is not the most optimal solution. The worst case scenario (if there are no matches) is that for every element in the first string, we will have to iterate through every element in the second string. This has a time complexity of O(nm) where n and m are the size of the given strings.

If you haven’t heard of Big O notation, check out this great article which goes into all the details. Understanding Big O notation and being able to communicate how optimal your solution is to an interviewer is an extremely important part of any technical interview.

Try it Out:

Head on over to Coderbyte and try and solve the problem in a more optimized way. Remember to come back next week where I’ll discuss some other solutions and common pitfalls to this problem. Good luck coding :)

Our newsletter 📫

We’re going to be sending out a small, feature reveal snippet every time we release something big, so our community is the first to know when we break out something new. Give us your email here and we'll add you to our "first to know" list :)

Latest comments (48)

Collapse
 
anonymous999 profile image
Anonymous • Edited
const FindIntersection = arr => {
  return arr[0].match(/\d+/g).filter(v => (
    arr[1].match(/\d+/g).includes(v)
  )).join`,` || false
}
Collapse
 
sxync profile image
SaiKumar Immadi • Edited

A simple and straightforward O(m+n) solution.

const FindIntersection = array => {
  const commonNumbers = [];

  const array1 = array[0].split(", ").map(num => Number(num));
  const array2 = array[1].split(", ").map(num => Number(num));

  let index1 = 0;
  let index2 = 0;

  while (index1 < array1.length && index2 < array2.length) {
    if (array1[index1] < array2[index2]) {
      index1 += 1;
    } else if (array2[index2] < array1[index1]) {
      index2 += 1;
    } else {
      commonNumbers.push(array1[index1]);
      index1 += 1;
      index2 += 1;
    }
  }

  return commonNumbers.join(", ");
};

EDIT: I just checked the next article and it has the same solution listed. Sorry I did not check that before posting this here.

Collapse
 
vaibhavyadav1998 profile image
Vaibhav Yadav • Edited

In JavaScript.

function findIntersection(strArr) {
  const arr = strArr.join(",").replace(/\s+/g, "").split(",");
  const count = {};
  const common = [];

  arr.map(i => count[i] ? count[i]++ : count[i] = 1);

  for (const i in count) {
    if (count[i] > 1) {
      common.push(parseInt(i, 10));
    }
  }

  return common.length ? common.sort((a, b) => a > b).join(",") : false;
}
Collapse
 
sohammondal profile image
Soham Mondal

This is my O(n) solution. We don't need to parse any of the strings to an integer.


const findIntersection = (arr) => {

  // n1 - larger array
  // n2 - smaller array

  let n1, n2;

  if (arr[0].split(',').length > arr[1].split(',').length) {
    n1 = arr[0].split(',');
    n2 = arr[1].split(',');
  } else {
    n1 = arr[1].split(',');
    n2 = arr[0].split(',');
  }

  let len = n1.length;

  // store the common items
  let common = [];

  for (let i = 0; i < len; i++) {

    // check if an item of one array (larger one) exists in the other array (smaller one)
    if (n2.includes(n1[i])) {
      common.push(n1[i]);
    }


  }

  return common.length ? common.join() : "false" ;
}

Collapse
 
teaglebuilt profile image
dillan teagle • Edited
import pytest



def findIntersection(arr):
    unique = list()
    duplicates = []
    for string in arr: 
        for char in string.split(','):
            if int("".join(char)) in unique:
                duplicates.append(int("".join(char)))
            else:
                unique.append(int("".join(char)))

    return duplicates



@pytest.mark.parametrize(
    ("arr_s", "expected"),
    (["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"], [1, 4, 13]),
)
def test(arr_s, expected):
    assert findIntersection(arr_s) == expected




if __name__ == "__main__":
    x = ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
    print(findIntersection(x))
Collapse
 
marko911 profile image
Marko Bilal

I dont understand why anyone would ask you this in an interview ? A massive red flag for me.

Collapse
 
leoalipazaga profile image
Leonardo Alipazaga
function FindIntersection(strArr) {
  return
    strArr
    .map(e => e.split(','))
    .reduce((listA, listB) => {
      const listFiltered = listA.filter(itemA => listB.includes(itemA));
      return listFiltered.length ? listFiltered : false;
    });
}
Collapse
 
gabgab2003 profile image
DownloadPizza • Edited

Kotlin (any number of strings): pl.kotl.in/Lgfcz5KnV?theme=darcula

Collapse
 
gabgab2003 profile image
DownloadPizza • Edited
use std::cmp::Ordering;

fn main() {
    let a = find_intersections([
        String::from("-2, -1, 1, 1, 1, 2, 3, 6"),
        String::from("-1, 1, 1, 3, 4, 5, 6")
    ]);
    println!("{}", a);
}

fn find_intersections(arr: [String; 2]) -> String {
    let mut inter : Vec<isize> = Vec::new();
    let mut a = arr[0].split(",").map(
        |e| e.trim().parse::<isize>().unwrap()
    );
    let mut b = arr[1].split(",").map(
        |e| e.trim().parse::<isize>().unwrap()
    );

    let mut tmp_a = a.next();
    let mut tmp_b = b.next();

    while tmp_a.is_some() && tmp_b.is_some() {
        match tmp_a.unwrap().partial_cmp(&tmp_b.unwrap()).expect("NAN is evil") {
            Ordering::Less => tmp_a = a.next(),
            Ordering::Equal => {inter.push(tmp_a.unwrap()); tmp_a = a.next();tmp_b = b.next()},
            Ordering::Greater => tmp_b = b.next(),
        }
    }

    if inter.is_empty() {
        return String::from("false")
    }
    return inter.into_iter().map(|x| x.to_string()).collect::<Vec<String>>().join(", ")
}

A rust solution, im quite new to rust, so this is probably quite ugly

Collapse
 
stoiandan profile image
Stoian Dan • Edited

Python solution, not in a nice format, and assuming the input are two integer arrays:


def common_arr(first, second):
    mi, ma = (first,second) if len(first) <= len(second) else (second,first)
    common = []
    i = 0
    j = 0
    while(i < len(mi)):
        if(mi[i] == ma[j]):
                common.append(mi[i])
                i += 1
                if j < len(ma)-1:
                    j += 1
                else:
                    break
        elif mi[i] < ma[j]:
            i += 1
        else:
            if j < len(ma)-1:
                j += 1
            else:
                break

    return common

arr = common_arr([1,2,3,4,5,9],[3,5,6,8,9])
print(arr)

So idea:
You iterate over the smallest array, at each step, you are in one of 3 situations

arr1[i] == arra2[j] // you increment i and j because of the invariant, that says the arrays are sorted, so if you found a match you can safely increment.

arr1[i] < arr2[j] // since at index i we have the smallest element, we increment that one because being sorter we ca safely increment until we hit what is at index j or greater

arr1[i] < arr2[j] // same as above only for j

Collapse
 
assafsch profile image
Assaf Schwartz • Edited

Not a JS guy, so I decided to do it in Python.
As an interviewer, for these kind of question I'm not a fan of leveraging too much of the language built-ins (such as sets), as it masks algorithmic thinking, which I believe is an important part of the interview.

My solution uses a dictionary to count the number of occurrences for every item.

from collections import defaultdict

def find_intersect(strings):
    a, b = strings
    a = a.split(",")
    b = b.split(",")
    counter = defaultdict(int)
    intersect = list()
    for idx in range(max(len(a), len(b))):
        if idx < len(a):
            item = int(a[idx])
            counter[item]=counter[item]+1
            if counter[item] > 1:
                intersect.append(item)
        if idx < len(b):
            item = int(b[idx])
            counter[item]=counter[item]+1
            if counter[item] > 1:
                intersect.append(item)
    return intersect if intersect else "false"
Collapse
 
elisabethgross profile image
elisabethgross

I agree about not leveraging too many language built-ins, or, making sure to talk about the time complexity of those built-ins!

Collapse
 
lisabenmore profile image
Lisa Benmore • Edited

fwiw, another js option:

jsfiddle.net/4usxLhyo/1/

sorry, first post, not sure how to get the js syntax highlighting...
Edit: thanks @elisabethgross for the syntax highlighting help!

console.clear()

const one = '1,3,5,5,7,9,9';
const two = '2,4,5,6,8,9,9';
const three = '1,3,5,7,9';
const four = '2,4,6,8';

function findThings (str1, str2) {
  const arr1 = str1.split(',');
  const arr2 = str2.split(',');
  const result = [];

  for (const i of arr1) {
    if (arr2.indexOf(i) > -1) {
      result.push(i);
      arr2.splice(arr2.indexOf(i), 1);
    }
  }

  return result.length ? result : false;
}

console.log(findThings(one, two));
console.log(findThings(three, four )); ```


Collapse
 
elisabethgross profile image
elisabethgross • Edited

Nice! If you use the triple backticks, you can write javascript next to the top triple backticks. Check out this helpful markdown cheat sheet!

Collapse
 
firee80 profile image
Firee80

Hi! I wrote a solution that should be able to handle n-number of lines.
Also it does not care if there are duplicate numbers or they are out of order.
It just uses .map and .reduce.. probably it still could be optimized by using Set.

const lines = ['1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8']

const mapArrayToHashTable = items => {
  return items.reduce((last, item) => ({...last, [''+item]: item}), {}) 
}

const getHashTable = line => {
  const textNumbers = line.split(',')
  const numbers = textNumbers.map(number => parseInt(number))
  return mapArrayToHashTable(numbers)
}

const [firstTable, ...otherTables] = lines.map(getHashTable)

const result = otherTables.reduce((last, table) => {
  const keyObjs = Object.keys(table).map(key => last[key] ? {[key]: last[key]} : {})
  return keyObjs.reduce((last, keyObj) => ({...last, ...keyObj}), {})
}, firstTable)

console.log(Object.values(result)) // returns [2,4,6]
Collapse
 
firee80 profile image
Firee80

simplified the solution by using Sets and corrected the answer to correspond the assignment

const lines = ['1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8']

function FindIntersection(lines) {
  const getSet = line => new Set(line.split(',').map(number => parseInt(number)))
  const [firstSet, ...otherSets] = lines.map(getSet)
  const result = [...otherSets.reduce((lastSet, set) => new Set([...set].filter(number => lastSet.has(number))), firstSet)]
  return result.length > 0 ? result : 'false'
}

console.log(FindIntersection(lines)) // outputs: [2,4,6]
Collapse
 
firee80 profile image
Firee80

couldn't help myself.. improved the performance by sorting sets and checking result set. Changed the api from array input to n-amount of params. Also input is filtered from not a number

function FindIntersection(...lines) {  
  const getSet = (line = '') => {
    const numbers = line.split(',').map(number => parseInt(number))
    return new Set(numbers.filter(number => !isNaN(number)))
  }
  const sets = lines.map(getSet)
  const [shortestSet, ...otherSets] = [...sets].sort((setA, setB) => setA.size - setB.size)
  const defaultSet = lines.length > 1 ? shortestSet : new Set([])
  const resultSet = otherSets.reduce((resultSet, set) => {
    const commonNumbers = [...resultSet].filter(number => set.has(number))
    return new Set(commonNumbers)
  }, defaultSet)
  const result = [...resultSet]
  return result.length > 0 ? result : 'false'
}

console.log(FindIntersection()) // outputs: false
console.log(FindIntersection('1')) // outputs: false
console.log(FindIntersection('2', '3')) // outputs: false
console.log(FindIntersection('-1, 0', '0')) // outputs: [0]
console.log(FindIntersection('a, 3', 'b, c, 3')) // outputs: [3]
console.log(FindIntersection('-2, 3', '-4, -2')) // outputs: [-2]
console.log(FindIntersection('1,2,3,4', '2,3,4,5', '3,4,5,6')) // outputs: [3, 4]
console.log(FindIntersection('1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8')) // outputs: [2, 4, 6]
console.log(FindIntersection(...['1, 3, 4, 7, 13', '1, 2, 4, 13, 15'])) // outputs: [1, 4, 13]
Thread Thread
 
firee80 profile image
Firee80

Decided to have a one more improvement for performance (when one Set has size = 0, so no need to reduce other Sets. Also result from reduce is directly an array of numbers).
Also my apologies to @elisabethgross as I noticed the tag #codenewbie in the challenge and my answer isn't really for newbies.

function FindIntersection(...lines) {  
  const getSet = (line = '') => {
    const numbers = line.split(',').map(number => parseInt(number))
    return new Set(numbers.filter(number => !isNaN(number)))
  }
  const sets = lines.map(getSet)
  const [shortestSet, ...otherSets] = [...sets].sort((setA, setB) => setA.size - setB.size)
  const setsToReduce = shortestSet && shortestSet.size > 0 ? otherSets : [] 
  const defaultCommonNumbers = lines.length > 1 ? [...shortestSet] : []
  const resultCommonNumbers = setsToReduce.reduce((commonNumbers, set) => 
    commonNumbers.filter(number => set.has(number)), defaultCommonNumbers)
  return resultCommonNumbers.length > 0 ? resultCommonNumbers : 'false'
}

console.log(FindIntersection()) // outputs: false
console.log(FindIntersection('1')) // outputs: false
console.log(FindIntersection('2', '3')) // outputs: false
console.log(FindIntersection('-1, 0', '0')) // outputs: [0]
console.log(FindIntersection('a, 3', 'b, c, 3')) // outputs: [3]
console.log(FindIntersection('-2, 3', '-4, -2')) // outputs: [-2]
console.log(FindIntersection('1,2,3,4', '2,3,4,5', '3,4,5,6')) // outputs: [3, 4]
console.log(FindIntersection('1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8')) // outputs: [2, 4, 6]
console.log(FindIntersection(...['1, 3, 4, 7, 13', '1, 2, 4, 13, 15'])) // outputs: [1, 4, 13]
Collapse
 
orionaegis profile image
Orion Aegis
def sortedIntersection([a,b]):
  return any([map(set,a.split(', ')).intersection(b.split(', '))])

Would be the easiest to implement (I'm on my phone so I can't check it, also, python)

Collapse
 
hariadon profile image
hariadon

// I believe key here is that both arrays are sorted
function FindIntersection (strArr) {
const inBothStrings = []
const arr1 = strArr[0].split(', ')
const arr2 = strArr[1].split(', ')

let i=0,j=0;
while (i<arr1.length&&j<arr2.length){

//casting to numbers
let a = arr1[i]|0;
let b = arr2[j]|0;

if(a==b){
inBothStrings.push(a)
i++;
j++;
}
else if(a>b){

j++;
}
else if(b>a){
i++;
}

}

return inBothStrings.join(',')
}

Collapse
 
elisabethgross profile image
elisabethgross

Bingo! Nice work!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.