Count Number of Pairs With Absolute Difference K

Gulshan KumarGulshan Kumar
1 min read

Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.

The value of |x| is defined as:

  • x if x >= 0.

  • -x if x < 0.

LeetCode Problem - 2006

class Solution {
    // Function to count pairs in the array with a difference of k
    public int countKDifference(int[] nums, int k) {
        int count = 0; // Initialize count of pairs
        for(int i=0; i<nums.length; i++){ // Loop through the array
            for(int j=i+1; j<nums.length; j++){ // Iterate over elements ahead of the current element
                int flag = Math.abs(nums[i] - nums[j]); // Calculate the absolute difference between the elements
                if(flag == k) count++; // If the absolute difference equals k, increment count
            }
        }
        return count; // Return the count of pairs with a difference of k
    }
}
0
Subscribe to my newsletter

Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gulshan Kumar
Gulshan Kumar

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.