Showing posts with label programming questions. Show all posts
Showing posts with label programming questions. Show all posts

Monday, 8 April 2024

Implementing a Stack Data Structure in Java Using ArrayList

 

A stack is a fundamental data structure in computer science that follows the Last In, First Out (LIFO) principle. Imagine a stack of plates where you can only add or remove the top plate. Similarly, in a stack data structure, elements are added and removed from the top, allowing for efficient last-in, first-out access.

 

Key operations of Stack

a.   Push Operation: The push operation adds an element to the top of the stack. When you push an element onto a stack, it becomes the new top element.

b.   Pop Operation: The pop operation removes the top element from the stack. It returns the removed element and updates the stack's top pointer to the next element.

c.    Size Operation: The size operation returns the number of elements currently present in the stack.


 

Use Cases of Stack

Stacks is used in various areas of computer science and software development:

 

1.   Function Call Stack: In programming languages like Java, C++, and Python, a function call stack is used to manage function calls and local variables.

2.   Expression Evaluation: Stacks are commonly used to evaluate arithmetic expressions, postfix, and infix expressions.

3.   Undo Mechanisms: Many applications use stacks to implement undo functionality, where each operation performed is pushed onto the stack, allowing users to undo their actions in reverse order.

4.   Browser History: Web browsers use a stack to store the history of visited web pages, enabling users to navigate back and forth.

5.   Backtracking Algorithms: Stack-based backtracking algorithms are used to solve problems such as maze traversal, graph traversal, and puzzle solving.

 

Implementing a Stack using ArrayList in Java:

Below is a simple implementation of a stack data structure using the ArrayList class in Java:

 

ArrayStack.java 

package com.sample.app.util;

import java.util.ArrayList;

public class ArrayStack<T> {

	private final ArrayList<T> stack;

	public ArrayStack() {
		stack = new ArrayList<>();
	}

	public ArrayStack(int initSize) {
		stack = new ArrayList<T>(initSize);
	}

	public void push(T obj) {
		stack.add(obj);
	}

	public T pop() {
		if (isEmpty()) {
			throw new IllegalStateException("Stack is empty");
		}
		return stack.remove(stack.size() - 1);
	}

	public boolean isEmpty() {
		return stack.isEmpty();
	}

	public int size() {
		return stack.size();
	}

	public void clear() {
		stack.clear();
	}

	public void print() {
		System.out.println("\nElements in the stack are");
		for (int i = stack.size() - 1; i >= 0; i--) {
			System.out.println(stack.get(i));
		}
	}

}

 

ArrayStackDemo.java

package com.sample.app;

import com.sample.app.util.ArrayStack;

public class ArrayStackDemo {
	
	public static void main(String[] args) {
		ArrayStack<Integer> stack = new ArrayStack<> ();
		
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		
		stack.print();
		
		System.out.println("\nPop two elements from stack");
		
		stack.pop();
		stack.pop();
		
		stack.print();
		
		System.out.println("\nAdd an element 6 to the stack");
		stack.push(6);
		stack.print();
		
	}

}

 

Output

Elements in the stack are
5
4
3
2
1

Pop two elements from stack

Elements in the stack are
3
2
1

Add an element 6 to the stack

Elements in the stack are
6
3
2
1

 

You may like


Sunday, 8 October 2023

Program to create append only log file in Java

Write a program to create an append-only log file that can be used to log messages. The log file should be able to grow to a certain threshold size before it is backed up and a new log file is created.

Make sure that your application handles below requirements.

a.   The log file should be thread-safe.

b.   The log file should be configurable, so that you can specify the threshold size, backup directory, and other parameters.

c.    The log file should be efficient, so that it does not impact the performance of the system.

 

 Find the below working application.


ThreadSafeLogFile.java

package com.sample.app;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class ThreadSafeLogFile {
	private final Object LOCK = new Object();
	private static final String DEFAULT_LOG_FILE = "myLogFile.log";
	private static long DEFAULT_FILE_SIZE_IN_BYTES = 10 * 1024 * 1024; // Default threshold size (10MB)
	private static String DEFAULT_BACKUP_DIRECTORY = "backup_logs"; // Default backup directory

	private String logFileName;
	private long maxLogFileSizeBytes;
	private String backupDirectory;

	private void backupLogFile() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Date now = new Date();
		String timestamp = dateFormat.format(now);
		String logFileNameAlone = new File(logFileName).getName();
		String backupFileName = backupDirectory + File.separator + logFileNameAlone.split("\\.")[0] + "_" + timestamp
				+ ".log";

		try {
			Files.copy(new File(logFileName).toPath(), new File(backupFileName).toPath());
			Files.delete(new File(logFileName).toPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ThreadSafeLogFile() {
		this(DEFAULT_LOG_FILE);
	}

	public ThreadSafeLogFile(String logFileName) {
		this(logFileName, DEFAULT_FILE_SIZE_IN_BYTES);

	}

	public ThreadSafeLogFile(String logFileName, long maxLogFileSizeBytes) {
		this(logFileName, maxLogFileSizeBytes, DEFAULT_BACKUP_DIRECTORY);
	}

	public ThreadSafeLogFile(String logFileName, long maxLogFileSizeBytes, String backupDirectory) {
		if (logFileName == null || logFileName.isEmpty()) {
			throw new IllegalArgumentException("logFileName is null or empty");
		}

		if (!logFileName.endsWith(".log")) {
			logFileName = logFileName + ".log";
		}
		this.logFileName = logFileName;

		if (maxLogFileSizeBytes < 1024) {
			throw new IllegalArgumentException("maxLogFileSizeBytes is < 1024");
		}
		this.maxLogFileSizeBytes = maxLogFileSizeBytes;

		if (backupDirectory == null || backupDirectory.isEmpty()) {
			throw new IllegalArgumentException("backupDirectory is null or empty");
		}
		this.backupDirectory = backupDirectory;

		// Create the directory and any necessary parent directories
		File backupDir = new File(backupDirectory);
		if (!backupDir.exists()) {
			backupDir.mkdirs();
		}
	}

	public void appendLogMessage(String message) throws IOException {
		appendLogMessages(Arrays.asList(message));
	}

	public void appendLogMessages(List<String> logEntries) throws IOException {
		if (logEntries == null || logEntries.isEmpty()) {
			return;
		}

		synchronized (LOCK) {
			File logFile = new File(logFileName);

			if (logFile.length() >= maxLogFileSizeBytes) {
				backupLogFile();
			}

			try (FileWriter fileWriter = new FileWriter(logFileName, true);
					BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {

				for (String logEntry : logEntries) {
					if (logEntry == null) {
						continue;
					}
					bufferedWriter.write(logEntry);
					bufferedWriter.newLine();
				}

			}
		}
	}

}

App.java

package com.sample.app;

import java.io.IOException;

public class App {
	
	public static void main(String[] args) throws IOException {
		// Create a log file with threshold size 10KB
		ThreadSafeLogFile logFile = new ThreadSafeLogFile("/Users/Shared/chat-server.log", 10 * 1024, "/Users/Shared/backup");
		
		for(int i=0; i < 1000; i++) {
			logFile.appendLogMessage("This is message number " + i);
		}
	}

}


You may like

Interview Questions

Extend the thread to check it’s running status

Implement retry handler for a task in Java

Design an utility class to capture application metrics summary in Java

Utility class to get primitive type from wrapper type and vice versa

FNV hash algorithm implementation in Java

Controlling Randomness in Java: Exploring the Role of Seeds in java.util.Random

Tuesday, 30 June 2015

Learn Programming


Find element in a sorted matrix
Shift zeros to left and non-zeros to right
Reverse elements of array
Check whether a string is funny or not
Check for pangram
Reverse first n elements of array
Reverse string using recursion
Reverse array using recursion
Generic program to reverse elements of array
Rotate elements in an array (anti clock wise)
Frequency of numbers in array
Sort an array of three color balls
Longest positive sequence in array
Sort array of 0’s and 1’s
Print array in spiral shape
Solve following function
Retrieve unique instances of duplicate elements
Find start position of second sub array
Arrange elements of an array in random order
Move elements in even position to left and odd positions to right
Move elements in even position to left and odd positions to right (Maintain order)
Remove same adjacent character in a string
Find total deleted characters in string
Find lonely number in array
Find intersection of two arrays
Shift all zeros to left and non-zeros to right
Find pairs of numbers where sum equal to x
Sorted array to element:frequency format
Check whether two integers are equal without using comparison operator
Largest sum contiguous subarry
Find all paths
Find all paths from source to destination
Find duplicates from a given list of numbers
Bracket matching problem
Find common elements in two sorted arrays
Replace spaces in a character array with %20
Remove couples from a string
Find triplets where sum is equal to x
Find first non-repeating character in a string
Print distinct elements in every window of size k
Sort an array according to other array
Find smallest and second smallest element in array
Find minimum element in rotated array (Assume array is rotated clock wise)
How to know whether a number is power of 2
Count all set bits in an integer
Count all unset bits in an integer
Check whether nth bit is set or not
Check number is even or odd without division
Set nth bit of a number
Toggle nth bit
Low-level bit hacks that every programmer must know
Check for proper string
Minimum Number of Platforms Required for a Railway Station
Merge two sorted arrays
Find Next greater element
Partition Array
Linked List Java program
Transform one string to another
Program to build max heap
Program to build min heap
Merge Sort
Quick sort
Heap sort
print stars using recursion
Print up down stars
Print number of dots
Draw triangle using recursion
multiply two numbers recursively
compute exponent recursively
Print numbers from n to 0 recursively
Print numbers from 0 to n recursively
Reverse a string using recursion
Check for a prime number using recursion
Recursion to sum numbers from 1 to n
Recursive function to find minimum element in array
Recursion to find sum of elements in array
Recursive implementation of Binary search
Sum of digits using recursion
Recursive program to find maximum in array
Recursively find whether array is ordered or not
Find mean of array recursively
First element added with the second, the second with the third
Insertion Sort Java
Selection Sort Java
Infix to postfix converter program java
Find minimum element in array
Remove duplicate elements from array
Sum Of two arrays
Reverse an array in subset of N
Print the count of characters in duplicate array
Write a function to figure out if someone has won in a game of tic-tac-toe.
Find the missing element
Find the max product value of 3 numbers
Find the first element that appears an even number of times
Find the element that appears once in an array
Convert integers into roman equivalents
Count number of occurrences of a string
Find the permutations of a string
Add element to the end of stack
Reverse the elements of stack
Suppose there are 'N' stairs, a person wants to reach the top. Person can climb either 1 (or) 2 stairs at a time.Count the number of ways that a person can reach the top.
Java program to find cycle in a directed graph
Java program to find a cycle in undirected graph
Check whether number is even or odd using bitwise operator
Merge sort iterative implementation
Check whether array contain a duplicate value or not
Find the smallest digit and its positions in a given number
Implementing a Stack Data Structure in Java Using ArrayList