Facebook | Phone Screen | Monotony Change

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2022-02-02Added By Anonymous
Source: Link

Company: Facebook
Role: unknown
Interview Stage: Phone Screen
Location: unknown
Year: unknown

Original Post Content:

Facebook | Phone Screen | Monotony Changes

Count number of monotony changes in array - for e.g.

[6,5,4,1] -> 0
[2,3,4,5] -> 0
[2,3,4,5,6,5,4,1] -> 1
[2,3,4,1,5,6,5] -> 3

Interviewer said my code is wrong, spent lot of time to find out mistakes but couldn't find any edge cases where it will fail. Can anyone help me finding out mistakes.


def monotonic_changes(nums):
    n = len(nums)
    ans = 0
    if n <=2:
        return ans
  
    if nums[0] > nums[1]:
        dirn = -1
    elif nums[0] < nums[1]:
        dirn = 1
    else:
        # Handle case where first two elements are equal
        # This initial dirn might be incorrect if dirn is determined by first non-equal pair
        # The current code would proceed with an uninitialized dirn if nums[0] == nums[1]
        # Or, if this case should count as neither increasing nor decreasing initially,
        # the logic needs to skip or adjust the initial dirn setting until actual change occurs.
        pass # This path implies no initial direction set, which is an issue

    
    new_dirn = dirn # If nums[0] == nums[1], dirn is not initialized
    
    for i in range(2,n):
        if nums[i] > nums[i-1]:
            current_pair_dirn = 1
        elif nums[i] < nums[i-1]:
            current_pair_dirn = -1
        else:
            # nums[i] == nums[i-1]
            # Monotony does not change here. The direction from previous non-equal pair continues.
            # We should not update new_dirn in this case.
            continue # Skip to next iteration if no change
        
        # This is where the core logic issue lies for initialization and handling flats
        # If dirn was not set (because nums[0] == nums[1]), this comparison is problematic.
        # Also, new_dirn is always set based on current_pair_dirn even if dirn wasn't valid yet.
        if dirn is None: # Initial direction not yet established
            dirn = current_pair_dirn
            new_dirn = dirn
        elif dirn != current_pair_dirn:
            ans+=1
            dirn = current_pair_dirn # Update dirn to the new direction
            
    return ans
    
Comments