Program to count number of elements are placed at correct position in Python

Suppose we have a list of numbers called nums, we have to find the number of elements that are present in the correct indices, when the list was to be sorted.

So, if the input is like [2, 8, 4, 5, 11], then the output will be 2, as the elements 2 and 11 are in their correct positions. The sorted sequence will be [2, 4, 5, 8, 11]

Algorithm

To solve this, we will follow these steps ?

  • s := sort the list nums
  • count := 0
  • for i in range 0 to size of nums, do
    • if s[i] is same as nums[i], then
      • count := count + 1
  • return count

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, nums):
        s = sorted(nums)
        count = 0
        for i in range(len(nums)):
            if s[i] == nums[i]:
                count += 1
        return count

ob = Solution()
print(ob.solve([2, 8, 4, 5, 11]))

The output of the above code is ?

2

Alternative Approach Using Zip

We can simplify the solution using Python's zip() function to compare elements at corresponding positions ?

def count_correct_positions(nums):
    sorted_nums = sorted(nums)
    return sum(1 for original, sorted_val in zip(nums, sorted_nums) 
               if original == sorted_val)

# Test the function
nums = [2, 8, 4, 5, 11]
result = count_correct_positions(nums)
print(f"Original list: {nums}")
print(f"Sorted list: {sorted(nums)}")
print(f"Elements at correct positions: {result}")

The output of the above code is ?

Original list: [2, 8, 4, 5, 11]
Sorted list: [2, 4, 5, 8, 11]
Elements at correct positions: 2

How It Works

The algorithm compares each element in the original list with the corresponding element at the same index in the sorted list. When both elements match, it means the element is already in its correct position and we increment the counter.

In our example [2, 8, 4, 5, 11], element 2 is at index 0 in both original and sorted lists, and element 11 is at index 4 in both lists, giving us a count of 2.

Conclusion

This problem can be solved by comparing the original list with its sorted version element by element. The zip-based approach provides a more Pythonic solution with cleaner syntax.

Updated on: 2026-03-25T10:31:33+05:30

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements