blog-cover-image

Top Data Scientist Interview Questions Asked at Gojek, Meta, and Walmart

In this article, we will walk through real-world data scientist interview questions asked at these companies. Each question is solved and explained in detail, covering both the logic and the underlying concepts. Whether you are preparing for interviews or seeking to strengthen your data science fundamentals, this comprehensive guide will help you master essential topics.

Data Scientist Interview Questions from Gojek and Other Companies


1. Gojek: Calculate Online Duration from Driver Logs

Question

You have a sequence of logs from a driver that are timestamps which the app keeps sending every 15 seconds, e.g., [10, 25, 40, 100, 115, 130, ...]. If the gap between consecutive logs is more than 15 seconds, then the driver is considered offline. Find the number of hours the driver was online.

Understanding the Problem

The driver app is expected to send a "heartbeat" log every 15 seconds. If the interval between two consecutive logs exceeds 15 seconds, it means the driver was offline in between. The task is to compute the total online duration from the log timestamps.

Step-by-Step Solution

  • Compare each consecutive pair of timestamps.
  • If the difference is ≤ 15 seconds, add the difference to the total online duration.
  • If the difference is > 15 seconds, only add 15 seconds (since the driver was online for 15 seconds after the last heartbeat, then went offline until the next log).
  • Sum up all online durations and convert the total seconds to hours.

Sample Input


logs = [10, 25, 40, 100, 115, 130]

Python Implementation


def online_hours(logs):
    online_seconds = 0
    for i in range(1, len(logs)):
        diff = logs[i] - logs[i-1]
        if diff <= 15:
            online_seconds += diff
        else:
            online_seconds += 15
    return online_seconds / 3600  # convert seconds to hours

logs = [10, 25, 40, 100, 115, 130]
print(online_hours(logs))

Step-by-Step Calculation

Log Next Log Difference (s) Added to Online Time (s)
10 25 15 15
25 40 15 15
40 100 60 15
100 115 15 15
115 130 15 15

Total online seconds: 15 + 15 + 15 + 15 + 15 = 75 seconds.
Total online hours: \( \frac{75}{3600} \approx 0.0208 \) hours.

Concepts Involved

  • Time Series Analysis: Analyzing sequences of time-stamped data points.
  • Sliding Window: Comparing consecutive elements in a sequence.
  • Data Cleaning: Handling irregular intervals and missing data.

2. Meta: Remove Duplicates from a List

Question

Given a list, create a new list that does not include the duplicates of the original list.

Understanding the Problem

This is a classic data cleaning and transformation problem. Removing duplicates is essential for maintaining data integrity and ensuring accurate analysis.

Step-by-Step Solution

  • Iterate through the list and keep only the unique items.
  • If the order doesn't matter, converting to a set is the easiest solution.
  • If the order matters (keep the first occurrence), use an auxiliary set to track seen elements.

Python Implementation (Order Not Preserved)


original_list = [1, 2, 2, 3, 4, 3, 5]
unique_list = list(set(original_list))
print(unique_list)  # Output may be [1, 2, 3, 4, 5] but order is not guaranteed

Python Implementation (Order Preserved)


def remove_duplicates(lst):
    seen = set()
    unique = []
    for item in lst:
        if item not in seen:
            unique.append(item)
            seen.add(item)
    return unique

original_list = [1, 2, 2, 3, 4, 3, 5]
print(remove_duplicates(original_list))  # Output: [1, 2, 3, 4, 5]

Concepts Involved

  • Set Data Structure: Stores unique elements, no duplicates.
  • Hashing: Efficiently determines if an element is already seen.
  • Data Cleaning: Essential step in preprocessing for machine learning.

Time Complexity Analysis

  • Using set (unordered): \( O(n) \)
  • Using set with list (ordered): \( O(n) \)

3. Amazon: Pros and Cons of Random Forest

Question

Explain the pros and cons of Random Forest.

Understanding the Concept

Random Forest is a popular ensemble learning technique that operates by constructing multiple decision trees during training and outputting the mode or mean prediction of the individual trees.

How Random Forest Works

  • It builds multiple decision trees using random subsets of the data and features (bagging and feature randomness).
  • Aggregates the predictions (majority vote for classification, mean for regression).

Pros of Random Forest

  • High Accuracy: Aggregation of multiple trees reduces overfitting.
  • Robustness: Handles outliers and noise well.
  • Non-linearity: Captures complex, non-linear relationships.
  • Works with Categorical & Numerical Features: Versatile in handling various data types.
  • Feature Importance: Can estimate the relative importance of features.
  • Handles Missing Values: Can maintain accuracy even with missing data.

Cons of Random Forest

  • Computationally Intensive: Training and predicting with many trees can be slow and resource-heavy.
  • Less Interpretable: Unlike a single decision tree, the ensemble is a "black box".
  • Memory Usage: Storing multiple trees requires more memory.
  • Not Good for Extrapolation: Poor at predicting values outside the range of training data in regression tasks.
  • Can Overfit with Noisy Data: If not tuned properly, can still overfit.

Summary Table: Pros and Cons

Pros Cons
  • High accuracy
  • Robust to outliers
  • Handles non-linearity
  • Feature importance estimation
  • Works with different data types
  • Handles missing values
  • Computationally expensive
  • Less interpretable
  • High memory usage
  • Poor extrapolation
  • Can overfit with noisy data

When to Use Random Forest

  • When you prioritize prediction accuracy over model interpretability.
  • When your dataset contains a mix of categorical and numerical features.
  • When you have enough computational resources for training and prediction.

4. Walmart: Sub-Spaces Divided by Lines and Hyperplanes

Question

How many sub-spaces can 4 lines divide in 2D? How many sub-spaces can 4 hyperplanes divide in 3D?

Understanding the Problem

This is a classic combinatorial geometry question. The goal is to determine the maximum number of regions (sub-spaces) that can be formed by a given number of lines in a 2D plane or hyperplanes in a 3D space, assuming general position (no two are parallel, no three meet at a point, etc.).

1. Lines in 2D: Maximum Number of Regions

Let \( n \) be the number of lines in general position in 2D.

The formula for the maximum number of regions is:

\[ R(n) = \frac{n^2 + n + 2}{2} \]

For 4 lines: \[ R(4) = \frac{4^2 + 4 + 2}{2} = \frac{16 + 4 + 2}{2} = \frac{22}{2} = 11 \]

So, 4 lines can divide the 2D plane into a maximum of 11 regions.

How is this formula derived?

  • Each new line can intersect all the previous lines, thus adding as many new regions as the number of existing lines plus one.
  • So, for \( n \) lines: \( 1 \) (initial region) + \( n \) (first line) + \( n-1 \) (second) + ... + 1.
  • The sum is: \( 1 + \frac{n(n+1)}{2} \) = \( \frac{n^2 + n + 2}{2} \)

2. Hyperplanes in 3D: Maximum Number of Regions

For \( n \) hyperplanes in 3D (again, in general position), the formula is:

\[ R(n) = 1 + n + \frac{n(n-1)}{2} + \frac{n(n-1)(n-2)}{6} \]

For 4 hyperplanes: \[ R(4) = 1 + 4 + \frac{4 \times 3}{2} + \frac{4 \times 3 \times 2}{6} \]

Calculate step by step:

  • \( \frac{4 \times 3}{2} = 6 \)
  • \( \frac{4 \times 3 \times 2}{6} = \frac{24}{6} = 4 \)

So, \[ R(4) = 1 + 4 + 6 + 4 = 15 \]

Thus, 4 hyperplanes in 3D can divide the space into a maximum of 15 regions.

General Formula

The general formula for the maximum number of regions created by \( n \) hyperplanes in \( d \) dimensions is:

\[ R(n, d) = \sum_{k=0}^{d} \binom{n}{k} \]

  • \( \binom{n}{k} \) is the binomial coefficient (number of ways to choose \( k \) hyperplanes from \( n \)).

Concepts Involved

  • Combinatorics: Counting regions using binomial coefficients.
  • Geometry: Understanding the intersection of lines/planes in space.
  • General Position Assumption: Ensures maximum regions (no two are parallel, no three intersect at a point etc.).

Summary Table: Interview Questions and Concepts

Company Question Key Concepts Solution Summary
Gojek Calculate online hours from timestamp logs Time series, intervals, sequence processing Sum intervals ≤ 15s, add 15s for larger gaps, divide total by 3600 for hours
Meta Remove duplicates from list Set, hashing, data cleaning Use set or tracking seen elements for order; O(n) complexity
Amazon Pros and cons of random forest Ensemble learning, overfitting, interpretability High accuracy, robust, but slow and less interpretable
Walmart Regions divided by lines/hyperplanes Combinatorics, geometry 4 lines: 11 regions (2D); 4 hyperplanes: 15regions (3D)

Deeper Dive: Interview Problem Explanations and Variations

1. Gojek: Variations and Edge Cases

Let’s explore some edge cases and variations that could arise in this timestamp-log problem.

  • Edge Case 1: Only One Timestamp
    • If only one timestamp is present, the driver is considered online for 0 seconds, since there is no interval to measure.
    • Example: [10] → Online hours = 0.
  • Edge Case 2: Consecutive Gaps Much Larger Than 15 Seconds
    • Example: [10, 50, 100]
    • Calculation:
      • 10 → 50: diff = 40 → add 15
      • 50 → 100: diff = 50 → add 15
      Total = 30 seconds = 0.0083 hours.
  • Edge Case 3: Negative or Non-Increasing Timestamps
    • If timestamps are not strictly increasing or contain negative values, the data is invalid. Preprocessing to sort and validate timestamps is required.
  • Variation: Custom Interval
    • If the heartbeat interval is other than 15 seconds, the logic remains the same—just replace 15 with the new interval.

2. Meta: Remove Duplicates in Different Data Types

Removing duplicates isn’t limited to integers. Consider lists of strings, tuples, or even custom objects:


# List of strings
names = ['Alice', 'Bob', 'Alice', 'Eve']
unique_names = list(dict.fromkeys(names))
print(unique_names)  # Output: ['Alice', 'Bob', 'Eve']

# List of tuples
points = [(1, 2), (3, 4), (1, 2)]
unique_points = list(dict.fromkeys(points))
print(unique_points)  # Output: [(1, 2), (3, 4)]

Note: For lists of unhashable types (like lists of lists), you need to convert them to tuples or use a custom hash function.

Complexity and Performance

  • For large lists, built-in data structures like set or dict.fromkeys are highly optimized in Python 3.7+ where dictionaries preserve insertion order.
  • For custom objects, you must define __hash__ and __eq__ methods to ensure correct behavior.

3. Amazon: Random Forest – In-Depth Insights

Why Does Random Forest Reduce Overfitting?

Random Forest reduces overfitting by averaging multiple de-correlated trees. Each tree is trained on a bootstrap sample of the data, and at each split, only a random subset of features is considered. This randomness ensures that not all trees are the same and that noise or anomalies in the data do not dominate the model.

Random Forest in Practice

  • Parameter Tuning:
    • n_estimators – Number of trees in the forest.
    • max_depth – Maximum depth of each tree (controls overfitting).
    • max_features – Number of features to consider at each split.
  • Feature Importance Extraction:
    • Random Forest provides a ranking of features by how much they improve the split criterion (e.g., Gini impurity).
  • Applications:
    • Classification (fraud detection, spam filtering)
    • Regression (house price prediction, demand forecasting)

Limitations in Production

  • Large forests take time and memory, which can be problematic for real-time systems.
  • Model explainability is difficult; techniques like SHAP or LIME are used to interpret predictions.

4. Walmart: Geometry of Lines and Hyperplanes

Visualizing Regions in 2D and 3D

In 2D, each new line can intersect all previous lines, and each intersection creates new regions. For example:

  • 0 lines: 1 region (whole plane)
  • 1 line: 2 regions
  • 2 lines: up to 4 regions
  • 3 lines: up to 7 regions
  • 4 lines: up to 11 regions

This sequence matches the formula \( \frac{n^2 + n + 2}{2} \).

In 3D, hyperplanes (planes in three dimensions) can slice the space further. The count for 4 hyperplanes:

  • 0 hyperplanes: 1 region
  • 1 hyperplane: 2 regions
  • 2 hyperplanes: 4 regions
  • 3 hyperplanes: 8 regions
  • 4 hyperplanes: 15 regions

Extension: Higher Dimensions

The general formula for \( n \) hyperplanes in \( d \) dimensions:

\[ R(n, d) = \sum_{k=0}^{d} \binom{n}{k} \]

For example, in 4D, the number of regions with 4 hyperplanes is \[ R(4, 4) = \binom{4}{0} + \binom{4}{1} + \binom{4}{2} + \binom{4}{3} + \binom{4}{4} = 1 + 4 + 6 + 4 + 1 = 16 \]


Frequently Asked Questions (FAQ)

What if logs are missing or out of order in the Gojek problem?

You should first sort the timestamps, remove any invalid or duplicate entries, and only then perform the interval computation. Always validate and clean your data before analysis.

Is there a one-line solution to remove duplicates in Python?

Yes, using list(dict.fromkeys(your_list)) removes duplicates while preserving order (Python 3.7+).

When should I use Random Forest over Gradient Boosting?

Random Forest is preferred when you want a robust model with minimal hyperparameter tuning and can tolerate slower prediction times. Gradient Boosting is better for maximizing accuracy, especially on complex datasets, but requires more careful tuning and is more prone to overfitting.

How do these geometry questions relate to data science?

Combinatorial geometry is foundational in computational geometry, computer vision, and spatial data analysis. Understanding how planes and hyperplanes partition space is crucial for clustering, classification, and feature space segmentation.


Best Practices for Data Science Interviews

  • Clarify requirements: Always ask about edge cases, data validity, and input assumptions.
  • Write clean, robust code: Handle empty inputs, invalid data, and document your logic.
  • Analyze complexity: Discuss time and space complexity for all algorithms.
  • Explain concepts: Support your answers with theory and practical considerations.
  • Practice variations: Think about alternative inputs, generalizations, and related problems.

Conclusion

Mastering real-world data science interview questions requires a balance of algorithmic thinking, theoretical understanding, and practical coding skills. Whether you're calculating online durations from heartbeat logs (Gojek), cleaning data by removing duplicates (Meta), evaluating machine learning models like Random Forest (Amazon), or solving combinatorial geometry problems (Walmart), the underlying concepts are fundamental to data science practice.

By studying and practicing these types of questions, you’ll be well-equipped to tackle interviews at the world’s top companies—and to approach real data science problems with confidence.

Further Reading

Keep practicing, keep learning, and approach each data science interview question with curiosity and rigor!

Related Articles