Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Factorial and String-Length Sorting

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

Your question is Factorial and String-Length Sorting. 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

Walmart Global Tech services may need to calculate a numeric value and organize product labels for display. Implement one function that computes the factorial of a non-negative integer and sorts an array of strings by increasing string length.

Formal Specification

Implement factorial_and_sort(n, words):

  1. Compute n!, where n! = 1 * 2 * ... * n and 0! = 1.
  2. Return the sorted strings in nondecreasing order of length.
  3. Preserve the original relative order of strings with equal lengths. Python's built-in sorting is stable, but the ordering requirement must still be satisfied.
  4. Return a dictionary with keys factorial and sorted_words.

Examples

Example 1

Input: n = 5, words = ["milk", "egg", "water", "tea"]
Output: {"factorial": 120, "sorted_words": ["egg", "tea", "milk", "water"]}

5! is 120. The strings are ordered by lengths 3, 3, 4, and 5, with egg remaining before tea because they have equal length.

Example 2

Input: n = 0, words = ["apple", "kiwi", "pear"]
Output: {"factorial": 1, "sorted_words": ["kiwi", "pear", "apple"]}

0! is 1, and the two four-letter strings retain their original order.

Constraints

  • 0 <= n <= 20
  • 0 <= len(words) <= 10^4
  • Each string contains 0 to 100 characters
  • Strings may contain spaces, digits, or punctuation
  • The input list must not be modified in place

Function Signature

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