Find the Highest Occurring Digit in a Linked List Nodes
Last Updated :
03 Dec, 2023
Given a linked list, the task is to find the highest occurring digit in the linked list. Each node in the linked list contains a positive integer value. Analyze the digits present in these values and determine the digit that occurs the most frequently throughout the linked list.
Examples:
Input: 2 -> 11 -> 3 -> 2 -> 1
Output: 1
Explanation: In this example, the linked list is: 2 -> 11 -> 3 -> 2 -> 1. The digit 2 occurs twice, the digit 1 occurs thrice, and the digit 3 also occurs once. The digit 2 occurs in two nodes: the first node (2) and the fourth node (2). The digit 1 occurs in two nodes: the second node contains two times (11) and the fifth node (1). The digit 3 occurs in one node: the third node (3). Among these digits, the digit 1 has the highest occurrence with a count of 3. Therefore, the output is 1.
Input: 5 -> 5 -> 3 -> 2 -> 12
Output: 5
Explanation: In this example, the linked list is: 5 -> 5 -> 3 -> 2 -> 12. The digit 5 occurs twice, the digit 3 occurs once, and the digit 2 also occurs twice. The digit 5 occurs in two nodes: the first node (5) and the second node (5). The digit 3 occurs in one node : the third node (3). The digit 2 occurs in two node: the fourth node (2) and in the fifth node (2). Among these digits, the digit 5 and 2 has the highest occurrence with a count of 2 . Therefore, the output is 5 because 5 digit occurs before digit 2.
Approach: To solve the problem follow the below idea:
The intuition behind the approach is to iterate through the linked list and examine each node's value. By extracting individual digits from the value, we can keep track of their occurrences using an unordered map. The algorithm maintains a count for each digit encountered, updating the count whenever a digit is encountered again. Throughout the traversal, it identifies the digit with the highest count. Finally, it returns the digit that occurs the most frequently in the linked list. This approach efficiently determines the highest occurring digit by analyzing the digits within the linked list nodes and selecting the one with the maximum count.
Below are the steps of the approach:
- Initialize variables: maxCount and digitWithMaxCount.
- Start traversing the linked list from the head.
- For each node, extract its value.
- Count how many times each digit appears in the value.
- Update maxCount and digitWithMaxCount if a digit appears more times.
- Move to the next node and repeat steps 3-5.
- After traversing all nodes, return the digit with the highest count.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Define a structure for
// the linked list node
struct Node {
// Data value of the node
int data;
// Pointer to the next node
// in the list
struct Node* next;
};
// Function to find the highest occurring
// digit in the linked list
int highestOccurringDigit(Node* head)
{
// Initialize a map to store
// digit counts
unordered_map<int, int> digitCount;
// Initialize maximum count
int maxCount = 0;
// Initialize digit with the
// maximum count
int digitWithMaxCount = 0;
// Start traversing the
// linked list
Node* current = head;
while (current != NULL) {
// Get the value stored in
// the current node
int num = current->data;
// Extract individual digits from
// the number and count them
while (num != 0) {
// Extract the last digit
int digit = num % 10;
// Increment the count of
// the current digit
digitCount[digit]++;
// Update maxCount and
// digitWithMaxCount if needed
if (digitCount[digit] > maxCount
|| (digitCount[digit] == maxCount
&& digit > digitWithMaxCount)) {
maxCount = digitCount[digit];
digitWithMaxCount = digit;
}
// Remove the last digit
num /= 10;
}
// Move to the next node
/// in the linked list
current = current->next;
}
// Return the digit with
// the highest occurrence
return digitWithMaxCount;
}
// Function to create a new node with
// the given data value
Node* createNode(int data)
{
Node* newNode = new Node();
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Drivers code
int main()
{
// Create a linked list with
// sample data
Node* head = createNode(2);
head->next = createNode(11);
head->next->next = createNode(3);
head->next->next->next = createNode(2);
head->next->next->next->next = createNode(1);
// Find and print the highest occurring
// digit in the linked list
int highestDigit = highestOccurringDigit(head);
cout << "Highest Occurring Digit: " << highestDigit
<< endl;
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
// Define a class for the linked list node
class Node {
// Data value of the node
int data;
// Pointer to the next node in the list
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class Main {
// Function to find the highest occurring digit in the linked list
static int highestOccurringDigit(Node head) {
// Initialize a map to store digit counts
Map<Integer, Integer> digitCount = new HashMap<>();
// Initialize maximum count
int maxCount = 0;
// Initialize digit with the maximum count
int digitWithMaxCount = 0;
// Start traversing the linked list
Node current = head;
while (current != null) {
// Get the value stored in the current node
int num = current.data;
// Extract individual digits from the number and count them
while (num != 0) {
// Extract the last digit
int digit = num % 10;
// Increment the count of the current digit
digitCount.put(digit, digitCount.getOrDefault(digit, 0) + 1);
// Update maxCount and digitWithMaxCount if needed
if (digitCount.get(digit) > maxCount ||
(digitCount.get(digit) == maxCount && digit > digitWithMaxCount)) {
maxCount = digitCount.get(digit);
digitWithMaxCount = digit;
}
// Remove the last digit
num /= 10;
}
// Move to the next node in the linked list
current = current.next;
}
// Return the digit with the highest occurrence
return digitWithMaxCount;
}
// Function to create a new node with the given data value
static Node createNode(int data) {
return new Node(data);
}
public static void main(String[] args) {
// Create a linked list with sample data
Node head = createNode(2);
head.next = createNode(11);
head.next.next = createNode(3);
head.next.next.next = createNode(2);
head.next.next.next.next = createNode(1);
// Find and print the highest occurring digit in the linked list
int highestDigit = highestOccurringDigit(head);
System.out.println("Highest Occurring Digit: " + highestDigit);
}
}
// This code is contributed by Vikram_Shirsat
Python3
# Python code for the above approach
# Define a class for the linked list node
class Node:
# Constructor to initialize the node
def __init__(self, data):
self.data = data
self.next = None
# Function to find the highest occurring
# digit in the linked list
def highest_occuring_digit(head):
# Initialize a dictionary to store digit counts
digit_count = {}
# Initialize maximum count
max_count = 0
# Initialize digit with the maximum count
digit_with_max_count = 0
# Start traversing the linked list
current = head
while current is not None:
# Get the value stored in the current node
num = current.data
# Extract individual digits from the number and count them
while num != 0:
# Extract the last digit
digit = num % 10
# Increment the count of the current digit
digit_count[digit] = digit_count.get(digit, 0) + 1
# Update max_count and digit_with_max_count if needed
if digit_count[digit] > max_count or (digit_count[digit] == max_count and digit > digit_with_max_count):
max_count = digit_count[digit]
digit_with_max_count = digit
# Remove the last digit
num //= 10
# Move to the next node in the linked list
current = current.next
# Return the digit with the highest occurrence
return digit_with_max_count
# Function to create a new node with the given data value
def create_node(data):
return Node(data)
# Driver code
if __name__ == "__main__":
# Create a linked list with sample data
head = create_node(2)
head.next = create_node(11)
head.next.next = create_node(3)
head.next.next.next = create_node(2)
head.next.next.next.next = create_node(1)
# Find and print the highest occurring digit in the linked list
highest_digit = highest_occuring_digit(head)
print(f"Highest Occurring Digit: {highest_digit}")
C#
// C# Code
using System;
using System.Collections.Generic;
// Define a class for the linked list node
class Node
{
// Data value of the node
public int Data { get; set; }
// Pointer to the next node in the list
public Node Next { get; set; }
public Node(int data)
{
Data = data;
Next = null;
}
}
public class MainClass
{
// Function to find the highest occurring digit in the linked list
static int HighestOccurringDigit(Node head)
{
// Initialize a dictionary to store digit counts
Dictionary<int, int> digitCount = new Dictionary<int, int>();
// Initialize maximum count
int maxCount = 0;
// Initialize digit with the maximum count
int digitWithMaxCount = 0;
// Start traversing the linked list
Node current = head;
while (current != null)
{
// Get the value stored in the current node
int num = current.Data;
// Extract individual digits from the number and count them
while (num != 0)
{
// Extract the last digit
int digit = num % 10;
// Increment the count of the current digit
digitCount[digit] = digitCount.TryGetValue(digit, out int count) ? count + 1 : 1;
// Update maxCount and digitWithMaxCount if needed
if (digitCount[digit] > maxCount ||
(digitCount[digit] == maxCount && digit > digitWithMaxCount))
{
maxCount = digitCount[digit];
digitWithMaxCount = digit;
}
// Remove the last digit
num /= 10;
}
// Move to the next node in the linked list
current = current.Next;
}
// Return the digit with the highest occurrence
return digitWithMaxCount;
}
// Function to create a new node with the given data value
static Node CreateNode(int data)
{
return new Node(data);
}
public static void Main(string[] args)
{
// Create a linked list with sample data
Node head = CreateNode(2);
head.Next = CreateNode(11);
head.Next.Next = CreateNode(3);
head.Next.Next.Next = CreateNode(2);
head.Next.Next.Next.Next = CreateNode(1);
// Find and print the highest occurring digit in the linked list
int highestDigit = HighestOccurringDigit(head);
Console.WriteLine("Highest Occurring Digit: " + highestDigit);
}
}
// This code is contributed by guptapratik
JavaScript
// Define a class for the linked list node
class Node {
constructor(data) {
this.data = data; // Data value of the node
this.next = null; // Pointer to the next node in the list
}
}
// Function to find the highest occurring digit in the linked list
function highestOccurringDigit(head) {
// Initialize a map to store digit counts
const digitCount = new Map();
// Initialize maximum count
let maxCount = 0;
// Initialize digit with the maximum count
let digitWithMaxCount = 0;
// Start traversing the linked list
let current = head;
while (current !== null) {
// Get the value stored in the current node
let num = current.data;
// Extract individual digits from the number and count them
while (num !== 0) {
// Extract the last digit
const digit = num % 10;
// Increment the count of the current digit
digitCount.set(digit, (digitCount.get(digit) || 0) + 1);
// Update maxCount and digitWithMaxCount if needed
if (digitCount.get(digit) > maxCount || (digitCount.get(digit) === maxCount && digit > digitWithMaxCount)) {
maxCount = digitCount.get(digit);
digitWithMaxCount = digit;
}
// Remove the last digit
num = Math.floor(num / 10);
}
// Move to the next node in the linked list
current = current.next;
}
// Return the digit with the highest occurrence
return digitWithMaxCount;
}
// Function to create a new node with the given data value
function createNode(data) {
return new Node(data);
}
// Create a linked list with sample data
const head = createNode(2);
head.next = createNode(11);
head.next.next = createNode(3);
head.next.next.next = createNode(2);
head.next.next.next.next = createNode(1);
// Find and print the highest occurring digit in the linked list
const highestDigit = highestOccurringDigit(head);
console.log("Highest Occurring Digit: " + highestDigit);
OutputHighest Occurring Digit: 1
Time Complexity: O(N), where N is the number of nodes in the linked list.
Axillary Space: O(1) (constant) because the maximum number of entries in the unordered map remains constant regardless of the size of the linked list.
Similar Reads
Find extra node in the second Linked list
Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
7 min read
Write a function to get Nth node in a Linked List
Given a LinkedList and an index (1-based). The task is to find the data value stored in the node at that kth position. If no such node exists whose index is k then return -1.Example:Â Input: 1->10->30->14, index = 2Output: 10Explanation: The node value at index 2 is 10 Input: 1->32->12
11 min read
Print nodes of linked list at given indexes
Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
15+ min read
Find the Largest Number Using Four Nodes in a Singly Linked List
Given a singly linked list, the task is to find the largest number in the linked list using four nodes. Examples: Input: List: 2->5->3->4->6Output: 6543Explanation: Using the four nodes, we traverse the linked list and construct the largest number, which is 6543 Input: List: 1->7->
12 min read
Find the largest node in Doubly linked list
Given a doubly-linked list, find the largest node in the doubly linked list. Examples: Input: 10->8->4->23->67->88 Largest node is: 88 Output: 88 Input : 34->2->78->18->120->39->7 Largest node is: 120 Output :120 Approach Used: Initialize the temp and max pointer to
10 min read
Find first node of loop in a linked list
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to find the Starting node of the loop in the linked list if there is no loop in the linked list return -1.Example: Input: Output: 3Exp
14 min read
Find the common nodes in two singly linked list
Given two linked list, the task is to find the number of common nodes in both singly linked list. Examples: Input: List A = 3 -> 4 -> 12 -> 10 -> 17, List B = 10 -> 4 -> 8 -> 575 -> 34 -> 12 Output: Number of common nodes in both list is = 3 Input: List A = 12 -> 4 -
15+ min read
Find the Second Largest Element in a Linked List
Given a Linked list of integer data. The task is to write a program that efficiently finds the second largest element present in the Linked List. Examples: Input : List = 12 -> 35 -> 1 -> 10 -> 34 -> 1 Output : The second largest element is 34. Input : List = 10 -> 5 -> 10 Outpu
9 min read
Find the Previous Closest Smaller Node in a Singly Linked List
Given a singly linked list, the task is to find the previous closest smaller node for every node in a linked list. Examples: Input: 5 -> 6 -> 8 -> 2 -> 3 -> 4Output: -1 -> 5 -> 6 -> -1 -> 2 -> 3Explanation: For the first node 5, there is no previous closest smaller node
13 min read
Finding Median in a Sorted Linked List
Given A sorted linked list of N elements. The task is to find the median in the given Sorted Linked List.We know that median in a sorted array is the middle element. Procedure to find median of N sorted numbers: if N is odd: median is N/2th elementelse median is N/2th element + (N/2+1)th elementExam
14 min read