Interview Experience – Hackerrank (1 Hour, C++, JavaScript)

I had a one-hour technical interview on Hackerrank where I was asked two questions. One was a DSA question to be coded in C++, and the other was based on JavaScript.


Q1. Leetcode 658 – Find K Closest Elements

Link: https://leetcode.com/problems/find-k-closest-elements/description/
Given a sorted array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:

  • |a - x| < |b - x|, or
  • |a - x| == |b - x| and a < b

Example Input:

arr = [1,2,3,4,5], k = 4, x = 3  
Output: [1,2,3,4]

My C++ Code:

#include <cmath>
#include <cstdio>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int addNumbers(int a, int b) {
    return a+b;
}

// // // // // Input: arr = [1,2,3,4,5], k = 4, x = 3

int main() {
    // int size;
    vector<int>arr={23, 45, 67, 98};
    int k=2;
    int x=75;
    // cin>>size;
    // for (int i=0;i<size;i++){
    //     int temp;
    //     cin>>temp;
    //     arr.push_back(temp);
    // }
    vector<pair<int ,int>> diff;
    // vector<int> diff(arr.size(),0);
    for(int i=0;i<arr.size();i++){
        diff.push_back({abs(arr[i]-x),i});//O(n)
        // diff[i]=abs(arr[i]-x);
    }
    priority_queue<pair<int,int>>pq;
    for(int i=0;i<arr.size();i++){
        pq.push({diff[i].first,diff[i].second});//O(nlog(k))
        if(pq.size()>k) pq.pop();
    }
    vector<int>ans;
    while(pq.size()){
        pair<int,int> temp=pq.top();
        ans.push_back(arr[temp.second]);//O(k)
        // cout<<arr[temp.second];
        pq.pop();
    }
    sort(ans.begin(),ans.end());//O(k*log(k))
    for(int x:ans) cout<<x<<" ";
    return 0;
}

Q2. JavaScript – Flatten a Deeply Nested Array

Given a nested array like:

const nestedArray = [1, [2, 3], [4, [5]]];

Write a function to flatten it without using inbuilt functions like .flat().

Note: Interviewer asked to avoid inbuilt .flat() and recursion was allowed.

What I Said:
I suggested using recursion and checking if the element is an array using Array.isArray(), but I couldn’t complete the code in time.

What I initially wrote:

const flattenedArray = deeplyNestedArray.flat(Infinity);

Expected Approach Using Recursion (Not allowed to use .flat()):


Let me know what you think or how you would optimize this.

Verdict : Rejected

Comments (5)