Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan

Optimize Existing Code

MediumCoding00:00
Practice interviewer
In session
5 left
00:00

Your question is Optimize Existing Code. Take a moment with it on the right.

Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).

You need to log in / sign up to chat or submit.

Problem

This is a simplified version of a GitLab-style backend service that summarizes merge request activity for a project: which merge requests are open, which have gone stale, who's been approving things, and nudging stale authors by email. On a busy self-managed instance with a lot of history, calling any of these methods takes noticeably longer than it should.

class MergeRequestService
  def initialize(project)
    @project = project
  end

  def open_merge_requests
    MergeRequest.all.select { |mr| mr.project_id == @project.id && mr.status == "open" }
  end

  def stale_merge_requests(days = 14)
    open_merge_requests.select do |mr|
      (Time.now - mr.updated_at) / 86400 > days
    end
  end

  def approvers_summary
    summary = {}
    open_merge_requests.each do |mr|
      mr.approvals.each do |approval|
        user = User.find(approval.user_id)
        summary[user.username] ||= 0
        summary[user.username] += 1
      end
    end
    summary
  end

  def notify_stale_authors
    stale_merge_requests.each do |mr|
      author = User.find(mr.author_id)
      NotificationMailer.stale_mr_warning(author.email, mr.title).deliver_now
    end
  end
end

What optimizations can be done with this code? Explain where the cost is actually coming from.