702769. Count Number

Medium

Count Number

Slug: count-number4832

Difficulty: Medium

Id: 702769

Topic Tags: Arrays, Data Structures

Company Tags: None

Summary

This problem involves counting the number of occurrences of a specific target element in an unsorted array. The key concepts involved are arrays and data structures.

Detailed Explanation

Given an unsorted integer array arr and an integer k, write a function to count the number of times k appears in the array.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable count to 0, which will store the frequency of k.
  2. Iterate through each element x in the array.
  3. If x is equal to k, increment the count by 1.
  4. Return the final value of count.

The time complexity of this solution is O(n), where n is the length of the input array, because we need to traverse the entire array once. The space complexity is O(1), as we only use a constant amount of space to store the count.

Optimized Solutions

Java

View on GeeksforGeeks
public int countNumber(int[] arr, int k) {
    int count = 0;
    for (int x : arr) {
        if (x == k) {
            count++;
        }
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.