Element Appearing More Than 25% In Sorted Array - Easy - LeetCode
💻 coding

Element Appearing More Than 25% In Sorted Array - Easy - LeetCode

1 min read 208 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves finding an integer that appears more than 25% of the time in a sorted array.
  • 2The solution uses a dictionary to count occurrences of each integer in the array.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves finding an integer that appears more than 25% of the time in a sorted array."

Element Appearing More Than 25% In Sorted Array - Easy - LeetCode

Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time.

Return that integer.

Example 1:

Input: arr = [1,2,2,6,6,6,6,7,10]

Output: 6

Constraints:

1 <= arr.length <= 10^4

0 <= arr[i] <= 10^5

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.Array
{
 public class FindSpecialIntegerSoln
 {
 public int FindSpecialInteger(int[] arr)
 {
 var map = new Dictionary<int, int>();
 
 for (int i = 0; i < arr.Length; i++)
 {
 if (map.ContainsKey(arr[i]))
 {
 map[arr[i]]++;
 }
 else
 {
 map.Add(arr[i], 1);
 }
 }

 // As it is mentioned that there will be at least one number
 // that will be having more than 25% frequency count.
 int max = 0;
 int value = 0;
 foreach (var item in map)
 {
 if (max < item.Value)
 {
 max = item.Value;
 value = item.Key;
 }
 }

 return value;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Unit Tests:

using LeetCode.AskGif.Easy.Array;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.Array
{
 [TestClass]
 public class FindSpecialIntegerSolnTests
 {
 [TestMethod]
 public void FindSpecialIntegerSoln_First()
 {
 var arr = new int[] { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
 var output = 6;
 var res = new FindSpecialIntegerSoln().FindSpecialInteger(arr);

 Assert.AreEqual(res, output);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 10 June 2020 · 1 min read · 208 words

Part of AskGif Blog · coding

You might also like