Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Stable KL Divergence Computation

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

Your question is Stable KL Divergence Computation. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

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

Problem

Given two arrays of non-negative numbers p and q representing discrete probability distributions over the same support, write a function that returns the Kullback-Leibler divergence KL(p || q) using numerically stable computation. The function should normalize inputs if needed, reject invalid distributions, and avoid taking log(0) by using a small positive epsilon.

Constraints

  • 1 <= len(p) == len(q) <= 10^5
  • p[i] >= 0 and q[i] >= 0
  • At least one value in each array is positive
  • Use natural logarithm
  • Absolute error within 1e-9 is acceptable

Function Signature

def kl_divergence(p, q):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output