ai-code-detection / dataset /raw /raw_dataset.csv
joshnavip's picture
Initial commit: AI code detection project (without binary files)
b144cb7
Code_ID,Code_Text,"Label (0- HUMAN, 1-AI)",Source_Type,Generation_Prompt,Language
,"import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor # Import ThreadPoolExecutor for multi-threading
import urllib.robotparser
from urllib.parse import urlparse, urljoin # Import urlparse and urljoin for URL manipulation
def is_allowed(url, user_agent='*'):
parsed_url = urlparse(url)
base_url = f'{parsed_url.scheme}://{parsed_url.netloc}'
robots_url = urljoin(base_url, 'robots.txt')
rp = urllib.robotparser.RobotFileParser()
rp.set_url(robots_url)
rp.read()
return rp.can_fetch(user_agent, url)
def fetch_page(url):
if not is_allowed(url):
print(f'Scraping not allowed for {url}')
return None
try:
response = requests.get(url)
if response.status_code == 200:
print(f'Successfully fetched {url}')
soup = BeautifulSoup(response.content, 'html.parser')
return soup
else:
print(f'Failed to fetch {url} with status code {response.status_code}')
except Exception as e:
print(f'Exception occurred while fetching {url}: {e}')
return None
def extract_links(soup, base_url):
links = []
if soup:
for link in soup.find_all('a', href=True):
full_url = urljoin(base_url, link['href'])
links.append(full_url)
return links
def scrape_urls(urls, max_workers=5):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(fetch_page, url): url for url in urls}
results = []
for future in futures:
result = future.result()
if result:
results.append(result)
return results
def main():
start_url = 'https://example.com' # Replace with the URL you want to start scraping from
soup = fetch_page(start_url)
if not soup:
return
links = extract_links(soup, start_url)
pages = scrape_urls(links)
for page in pages:
if page:
title = page.find('title').get_text()
print(f'Page title: {title}')
if __name__ == '__main__':
main()",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
arr = np.random.randint(0, 10**6, size=10**7)
# For loop
def find_max(arr):
m = arr[0]
for num in arr:
if num > m:
m = num
return m
print(""Max with loop:"", find_max(arr))
print(""Max with np.max:"", np.max(arr))",1,DEEPAI,Write a NumPy program to generate a large NumPy array and write a function to find the maximum element using a for loop. Optimize it using NumPy's built-in functions.,PYTHON
,"import time # Import the time module to measure execution time
class LogExecutionTime: # Define a class for the decorator
def __init__(self, func): # Initialize the decorator with the function to be decorated
self.func = func # Store the function to be decorated
def __get__(self, instance, owner): # Define the descriptor method to handle instance methods
return lambda *args, **kwargs: self(instance, *args, **kwargs) # Return a lambda that passes the instance
def __call__(self, *args, **kwargs): # Make the class instance callable
instance = args[0] # Extract the instance from the arguments
start_time = time.time() # Record the start time
result = self.func(instance, *args[1:], **kwargs) # Call the original function with its arguments
end_time = time.time() # Record the end time
execution_time = end_time - start_time # Calculate the execution time
print(f""Execution time of {self.func.__name__}: {execution_time:.4f} seconds"") # Log the execution time
return result # Return the result of the original function call
# Example usage:
class ExampleClass: # Define an example class to demonstrate the decorator
@LogExecutionTime # Apply the decorator to the method
def example_method(self): # Define a method in the class
for _ in range(1000000): # A sample computation to add some delay
pass # Do nothing
# Instantiate the example class and call the decorated method
example = ExampleClass() # Create an instance of the ExampleClass
example.example_method() # Call the decorated method to see the execution time log",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
# Example 2D array
arr = np.array([[3, 2, 5],
[1, 4, 6],
[2, 1, 7]])
n = 1 # The column index to sort by (0-based)
# Get the indices that would sort the array by column n
sorted_indices = np.argsort(arr[:, n])
# Sort the array by the specified column
sorted_arr = arr[sorted_indices]
print(""Array sorted by column"", n, "":\n"", sorted_arr)",1,DEEPAI,Write a NumPy program to sort an given array by the nth column.,PYTHON
,"# Define a function to perform matrix multiplication of matrices A and B
def matrix_multiplication(A, B):
""""""
Perform matrix multiplication of matrices A and B.
Args:
A: First matrix (list of lists).
B: Second matrix (list of lists).
Returns:
Result of matrix multiplication (list of lists).
""""""
if len(A[0]) != len(B):
raise ValueError(""Number of columns in A must equal number of rows in B"")
# Number of rows and columns in resulting matrix
num_rows_A = len(A)
num_cols_B = len(B[0])
# Perform matrix multiplication using list comprehension
result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(num_cols_B)] for i in range(num_rows_A)]
return result
# Example usage:
if __name__ == ""__main__"":
# Example matrices A and B
A = [[1, 2, 3],
[4, 5, 6]]
B = [[7, 8],
[9, 10],
[11, 12]]
# Print the result of matrix multiplication
print(matrix_multiplication(A, B))
Output:",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
arr = np.array([9, 3, 5, 1, 8, 2, 7])
n = 4 # Number of elements to sort from the beginning
# Sort the first n elements
sorted_part = np.sort(arr[:n])
# Concatenate sorted part with the rest of the array
result = np.concatenate((sorted_part, arr[n:]))
print(""Array after sorting first"", n, ""elements:"", result)",1,DEEPAI,Write a NumPy program to sort the specified number of elements from beginning of a given array.,PYTHON
,"# Import the queue module to use PriorityQueue
import queue
# Import the threading module to use threads and locks
import threading
# Define a class for a thread-safe priority queue
class ThreadSafePriorityQueue:
def __init__(self):
# Initialize a PriorityQueue object to hold the items
self._queue = queue.PriorityQueue()
# Initialize a lock to ensure thread safety
self._lock = threading.Lock()
# Method to put an item into the priority queue
def put(self, item, priority):
# Acquire the lock to ensure thread safety
with self._lock:
# Put the item into the queue with its priority
self._queue.put((priority, item))
# Method to get an item from the priority queue
def get(self):
# Acquire the lock to ensure thread safety
with self._lock:
# Check if the queue is not empty
if not self._queue.empty():
# Get the item with the highest priority (lowest priority number)
priority, item = self._queue.get()
# Return the item
return item
else:
# Return None if the queue is empty
return None
# Example usage to demonstrate the thread-safe priority queue
if __name__ == ""__main__"":
# Define a producer function to add items to the queue
def producer(q):
# Add 5 items to the queue with their priority as their value
for i in range(5):
q.put(i, i)
# Define a consumer function to get items from the queue
def consumer(q):
# Continuously get items from the queue
while True:
# Get an item from the queue
item = q.get()
# If the item is None, break the loop (end of processing)
if item is None:
break
# Print the consumed item
print(""Consumed:"", item)
# Create an instance of the thread-safe priority queue
q = ThreadSafePriorityQueue()
# Create a producer thread to add items to the queue
producer_thread = threading.Thread(target=producer, args=(q,))
# Create a consumer thread to get items from the queue
consumer_thread = threading.Thread(target=consumer, args=(q,))
# Start the producer thread
producer_thread.start()
# Start the consumer thread
consumer_thread.start()
# Wait for the producer thread to finish
producer_thread.join()
# Add a sentinel value to the queue to signal the consumer to stop
q.put(None, None)
# Wait for the consumer thread to finish
consumer_thread.join()",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
arr = np.array([9, 3, 5, 1, 8, 2, 7])
k = 3 # Partition index
partitioned_arr = np.partition(arr, k)
print(""Partitioned array:"", partitioned_arr)",1,DEEPAI,"Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice)",PYTHON
,"import numpy as np
arr = np.array([3+4j, 1+7j, 3+2j, 2+5j, 1+2j])
# Use lexsort with imaginary part as the first key, real part as the second
sorted_indices = np.lexsort((np.imag(arr), np.real(arr)))
sorted_arr = arr[sorted_indices]
print(""Sorted array:"", sorted_arr)",1,DEEPAI,"Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.",PYTHON
,"# Define a class representing a node in a tree
class TreeNode:
def __init__(self, value):
self.value = value
self.children = [] # Initialize an empty list to store child nodes
def add_child(self, child_node):
self.children.append(child_node) # Add a child node to the list of children
# Define a class implementing a custom iterator for tree traversal
class TreeIterator:
def __init__(self, root):
self.stack = [root] # Initialize stack with root node
def __iter__(self):
return self
def __next__(self):
if not self.stack: # If stack is empty, no more nodes to traverse
raise StopIteration
node = self.stack.pop() # Get the top node from stack
for child in reversed(node.children): # Add children to stack in reverse order
self.stack.append(child)
return node.value
# Example usage:
if __name__ == ""__main__"":
# Create a tree with a root node and some child nodes
root = TreeNode(1)
root.add_child(TreeNode(2))
root.add_child(TreeNode(3))
root.children[0].add_child(TreeNode(4))
root.children[0].add_child(TreeNode(5))
root.children[1].add_child(TreeNode(6))
# Create a TreeIterator instance and iterate over the tree
tree_iterator = TreeIterator(root)
for value in tree_iterator:
print(value)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
arr = np.array([4, 2, 9, 7, 1])
indices = np.argsort(arr)
print(""Indices of sorted elements:"", indices)",1,DEEPAI,Write a NumPy program to get the indices of the sorted elements of a given array.,PYTHON
,"# Import necessary modules
from dataclasses import dataclass, field, fields, Field
from typing import Any, Callable, List, get_type_hints
# Custom exception for validation errors
class ValidationError(Exception):
pass
# Function to validate dataclass fields
def validate(instance):
cls = instance.__class__
hints = get_type_hints(cls)
# Iterate through fields and type hints
for name, type_hint in hints.items():
value = getattr(instance, name)
# Check if value matches type hint
if not isinstance(value, type_hint):
raise ValidationError(f""Field '{name}' expects {type_hint}, got {type(value)}"")
# Check for custom validators
field: Field = next(f for f in fields(cls) if f.name == name)
if 'validators' in field.metadata:
for validator in field.metadata['validators']:
validator(instance, value)
# Decorator to define a validator function
def validator(func: Callable[[Any, Any], None]):
if not callable(func):
raise ValueError(""Validator must be callable"")
func._is_validator = True
return func
# Function to define a field with validation
def field_with_validation(*, default: Any = None, default_factory: Callable[[], Any] = None, validators: List[Callable[[Any, Any], None]] = None) -> Field:
# Ensure only one of default or default_factory is provided
if default is not None and default_factory is not None:
raise ValueError('cannot specify both default and default_factory')
metadata = {}
# Attach validators to metadata
if validators:
metadata['validators'] = validators
# Define field with appropriate parameters
if default is not None:
return field(default=default, metadata=metadata)
elif default_factory is not None:
return field(default_factory=default_factory, metadata=metadata)
else:
return field(metadata=metadata)
# Dataclass representing a User with validation
@dataclass
class User:
# Define fields with validation
name: str
age: int = field_with_validation(default=0, validators=[
validator(lambda instance, value: value >= 0 or ValidationError(""Age must be non-negative"")),
validator(lambda instance, value: value <= 150 or ValidationError(""Age must be 150 or less""))
])
email: str = field_with_validation(default="""", validators=[
validator(lambda instance, value: ""@"" in value or ValidationError(""Invalid email address""))
])
# Example usage
try:
user = User(name=""Arsen"", age=30, email=""arsen@example.com"")
validate(user)
print(""User is valid"")
except ValidationError as e:
print(f""Validation error: {e}"")",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
ids = np.array([101, 102, 103, 104, 105])
heights = np.array([165, 170.5, 168.2, 172, 160.4])
idx = np.argsort(heights)
print(""Indices:"", idx)
print(""Sorted IDs:"", ids[idx])",1,DEEPAI,Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data,PYTHON
,"import heapq
# Define a class to represent a node in the graph
class Node:
def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
self.state = state # Current state
self.parent = parent # Parent node
self.action = action # Action taken to reach this node
self.cost = cost # Cost from start node to this node
self.heuristic = heuristic # Heuristic estimate of cost to goal
# Compare nodes based on total cost (cost + heuristic)
def __lt__(self, other):
return (self.cost + self.heuristic) < (other.cost + other.heuristic)
# Define the A* search function
def astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn):
# Initialize start node
start_node = Node(state=start_state, cost=0, heuristic=heuristic_fn(start_state))
# Priority queue for open nodes
open_nodes = []
heapq.heappush(open_nodes, start_node)
# Set of explored states
explored = set()
while open_nodes:
# Pop node with lowest total cost from priority queue
current_node = heapq.heappop(open_nodes)
# Check if goal state reached
if current_node.state == goal_state:
return get_solution(current_node)
# Add current state to explored set
explored.add(current_node.state)
# Generate successor states
for action in actions(current_node.state): # Fix: Call actions function with current state
next_state = transition_model(current_node.state, action)
if next_state not in explored:
cost = current_node.cost + cost_fn(current_node.state, action, next_state)
heuristic = heuristic_fn(next_state)
next_node = Node(state=next_state, parent=current_node, action=action, cost=cost, heuristic=heuristic)
heapq.heappush(open_nodes, next_node)
return None # No solution found
# Function to reconstruct the solution path
def get_solution(node):
path = []
while node:
path.append((node.state, node.action))
node = node.parent
return list(reversed(path))
# Example usage:
if __name__ == ""__main__"":
# Define example functions and parameters for pathfinding problem
def actions(state):
return ['up', 'down', 'left', 'right']
def transition_model(state, action):
if action == 'up':
return (state[0] - 1, state[1])
elif action == 'down':
return (state[0] + 1, state[1])
elif action == 'left':
return (state[0], state[1] - 1)
elif action == 'right':
return (state[0], state[1] + 1)
def cost_fn(state, action, next_state):
return 1
def heuristic_fn(state):
return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])
# Define start and goal states
start_state = (0, 0)
goal_state = (3, 3)
# Perform A* search
solution = astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn)
print(""Solution:"", solution) ",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
dt = [('name', 'U20'), ('height', 'f4'), ('class', 'i4')]
data = np.array([('Alice', 165, 2), ('Bob', 170.5, 1), ('Charlie', 168.2, 2), ('David', 172, 1), ('Eve', 160.4, 3)], dtype=dt)
print(np.sort(data, order=['class', 'height']))",1,DEEPAI,"Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort by class, then height if class are equal.",PYTHON
,"import os # Import the os module for interacting with the operating system
import shutil # Import the shutil module for file operations
import argparse # Import the argparse module for command-line argument parsing
def synchronize(source_dir, destination_dir):
# Ensure both directories exist
if not os.path.exists(source_dir):
print(f""Source directory '{source_dir}' does not exist."")
return
if not os.path.exists(destination_dir):
print(f""Destination directory '{destination_dir}' does not exist."")
return
# Iterate over files in source directory
for root, dirs, files in os.walk(source_dir):
# Get corresponding path in destination directory
relative_path = os.path.relpath(root, source_dir)
dest_path = os.path.join(destination_dir, relative_path)
# Ensure corresponding directory structure exists in destination
if not os.path.exists(dest_path):
os.makedirs(dest_path)
# Copy files from source to destination
for file in files:
source_file = os.path.join(root, file)
dest_file = os.path.join(dest_path, file)
shutil.copy2(source_file, dest_file)
print(f""Copied: {source_file} -> {dest_file}"")
print(""Synchronization complete."")
if __name__ == ""__main__"":
# Create argument parser
parser = argparse.ArgumentParser(description=""Synchronize files between two directories."")
# Add argument for source directory
parser.add_argument(""source"", help=""Source directory"")
# Add argument for destination directory
parser.add_argument(""destination"", help=""Destination directory"")
# Parse the command-line arguments
args = parser.parse_args()
# Call the synchronize function with the provided arguments
synchronize(args.source, args.destination)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
s = np.array([('A',160,10),('B',175,11),('C',155,9)],dtype=[('n','U10'),('h','i4'),('c','i4')])
print(np.sort(s,order='h')) ",1,PERPLEXITY,"Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort the array on height.",PYTHON
,"import json
# Define the Address and Person classes
class Address:
def __init__(self, street, city, state, zip_code):
self.street = street
self.city = city
self.state = state
self.zip_code = zip_code
class Person:
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
# Custom JSON Encoder
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Address):
return {
'__type__': 'Address',
'street': obj.street,
'city': obj.city,
'state': obj.state,
'zip_code': obj.zip_code
}
elif isinstance(obj, Person):
return {
'__type__': 'Person',
'name': obj.name,
'age': obj.age,
'address': obj.address
}
return json.JSONEncoder.default(self, obj)
# Custom JSON Decoder
def complex_decoder(dct):
if '__type__' in dct:
if dct['__type__'] == 'Address':
return Address(dct['street'], dct['city'], dct['state'], dct['zip_code'])
elif dct['__type__'] == 'Person':
address = dct['address']
if isinstance(address, dict):
address = complex_decoder(address)
return Person(dct['name'], dct['age'], address)
return dct
# Example usage
address = Address(""123 ABCD St."", ""Paris"", ""CA"", ""12345"")
person = Person(""Roslindis Bronwen"", 30, address)
# Serialize to JSON
person_json = json.dumps(person, cls=ComplexEncoder)
print(""Serialized JSON:"", person_json)
# Deserialize from JSON
decoded_person = json.loads(person_json, object_hook=complex_decoder)
print(""\nDecoded Object:"", decoded_person.name, decoded_person.age, decoded_person.address.street)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
a = np.array([[4,6],[2,1]])
print(np.sort(a,0), np.sort(a,1), np.sort(a, None), sep='\n') ",1,PERPLEXITY,"Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on flattened array.",PYTHON
,"import hashlib
class BloomFilter:
def __init__(self, size, hash_count):
self.size = size # Size of the bit array
self.hash_count = hash_count # Number of hash functions
self.bit_array = [0] * size # Bit array to store elements
def _hashes(self, item):
""""""Generate hash_count hashes for the item using different hash functions.""""""
hashes = []
for i in range(self.hash_count):
# Create a unique hash for each iteration
hash_result = int(hashlib.md5((str(item) + str(i)).encode()).hexdigest(), 16) % self.size
hashes.append(hash_result)
return hashes
def add(self, item):
""""""Add an item to the Bloom filter.""""""
hashes = self._hashes(item)
for hash_value in hashes:
self.bit_array[hash_value] = 1
def check(self, item):
""""""Check if an item is possibly in the Bloom filter.""""""
hashes = self._hashes(item)
return all(self.bit_array[hash_value] == 1 for hash_value in hashes)
# Example usage
size = 1000 # Size of the bit array
hash_count = 10 # Number of hash functions
bloom_filter = BloomFilter(size, hash_count)
# Add items to the Bloom filter
bloom_filter.add(""Red"")
bloom_filter.add(""Green"")
bloom_filter.add(""Blue"")
bloom_filter.add(""Orange"")
# Check for item membership
print(""Red in filter:"", bloom_filter.check(""Red"")) # Should be True
print(""Green in filter:"", bloom_filter.check(""Green"")) # Should be True
print(""Orange in filter:"", bloom_filter.check(""Orange"")) # Should be True
print(""Black in filter:"", bloom_filter.check(""Black"")) # Should be False (most likely)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
x = np.arange(7)
print(""Original:"", x)
print(""Powers (element-wise ^3):"", np.power(x, 3)) ",1,PERPLEXITY,Write a NumPy program to get the powers of an array values element-wise.,PYTHON
,"# Import the asyncio library for asynchronous programming
import asyncio
# Import nest_asyncio to handle nested event loops
import nest_asyncio
# Apply nest_asyncio to allow nested event loops
nest_asyncio.apply()
# Define the TaskScheduler class
class TaskScheduler:
def __init__(self):
# Initialize an empty list to store tasks
self.tasks = []
def schedule(self, coro, *args):
""""""Schedule a coroutine with given arguments.""""""
# Append the coroutine with its arguments to the tasks list
self.tasks.append(coro(*args))
async def run(self):
""""""Run all scheduled tasks concurrently.""""""
# Use asyncio.gather to run all tasks concurrently
await asyncio.gather(*self.tasks)
# Define an example coroutine that simulates a task
async def example_task(name, duration):
""""""An example coroutine that simulates a task.""""""
# Print a message when the task starts
print(f""Task {name} started, will take {duration} seconds."")
# Simulate a delay using asyncio.sleep
await asyncio.sleep(duration)
# Print a message when the task finishes
print(f""Task {name} finished."")
# Define the main coroutine for example usage
async def main():
# Create an instance of TaskScheduler
scheduler = TaskScheduler()
# Schedule example tasks with different durations
scheduler.schedule(example_task, ""A"", 2)
scheduler.schedule(example_task, ""B"", 3)
scheduler.schedule(example_task, ""C"", 1)
# Run all scheduled tasks concurrently
await scheduler.run()
# Run the main function using asyncio's event loop
asyncio.run(main())",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
x = np.arange(10)
print(""Original:"", x)
print(""Floor division by 3:"", np.floor_divide(x, 3)) ",1,PERPLEXITY,Write a NumPy program to get the largest integer smaller or equal to the division of the inputs.,PYTHON
,"from collections import OrderedDict
# Define a class for the caching system with LRU eviction policy
class LRUCache:
# Initialize the cache with a maximum capacity
def __init__(self, capacity):
self.capacity = capacity # Set the maximum capacity
self.cache = OrderedDict() # Use OrderedDict for O(1) access and ordering
# Get the value associated with the key from the cache
def get(self, key):
# If the key is not in the cache, return -1
if key not in self.cache:
return -1
# Move the accessed key to the end to indicate recent use
self.cache.move_to_end(key)
# Return the value associated with the key
return self.cache[key]
# Put a key-value pair into the cache
def put(self, key, value):
# If the key is already in the cache, update its value and move it to the end
if key in self.cache:
self.cache[key] = value
self.cache.move_to_end(key)
else:
# If the cache is at capacity, remove the least recently used item
if len(self.cache) == self.capacity:
self.cache.popitem(last=False) # Remove the first item (least recently used)
# Add the new key-value pair to the cache
self.cache[key] = value
# Example usage
if __name__ == ""__main__"":
# Create a cache with a capacity of 2
cache = LRUCache(2)
# Put key-value pairs into the cache
cache.put(1, 1)
cache.put(2, 2)
# Retrieve and print the value associated with key 1 (should be 1)
print(cache.get(1))
# Put a new key-value pair into the cache (evicting key 2)
cache.put(3, 3)
# Retrieve and print the value associated with key 2 (should be -1, as it was evicted)
print(cache.get(2))
# Retrieve and print the value associated with key 3 (should be 3)
print(cache.get(3))",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
x = np.arange(10)
print(""Original:"", x)
print(""True division by 3:"", x / 3) ",1,PERPLEXITY,"
Write a NumPy program to get true division of the element-wise array inputs.",PYTHON
,"# Import the Abstract Syntax Tree (AST) module
import ast
# Import the math module for mathematical functions and constants
import math
# Define a class for evaluating mathematical expressions
class MathExpressionEvaluator:
def __init__(self):
pass
# Method to evaluate mathematical expressions
def evaluate(self, expression):
try:
# Parse the expression into an Abstract Syntax Tree (AST)
parsed_expression = ast.parse(expression, mode='eval')
# Define the allowed names (functions and constants) for evaluation
allowed_names = {
'sin': math.sin,
'cos': math.cos,
'tan': math.tan,
'log': math.log,
'sqrt': math.sqrt,
**vars(math) # Include all functions and constants from the math module
}
# Evaluate the AST using a custom namespace that includes the allowed names
result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names)
return result
except SyntaxError:
print(""Invalid expression syntax."")
return None
except Exception as e:
print(""Error:"", e)
return None
# Example usage
if __name__ == ""__main__"":
evaluator = MathExpressionEvaluator()
# Evaluate mathematical expressions
print(""Evaluation Results:"")
print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4""))
print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4""))
print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)""))
print(""log(10) ="", evaluator.evaluate(""log(10)""))",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
print(np.logaddexp(np.log(1e-50), np.log(2.5e-50)))
print(np.logaddexp2(np.log(1e-50), np.log(2.5e-50))) ",1,PERPLEXITY,"Write a NumPy program to compute logarithm of the sum of exponentiations of the inputs, sum of exponentiations of the inputs in base-2.",PYTHON
,"# Import necessary modules
import json
import threading
import time
import signal
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Define the ConfigManager class to manage configurations
class ConfigManager:
def __init__(self, config_file):
# Initialize with the configuration file path
self.config_file = config_file
# Initialize the configuration data dictionary
self.config_data = {}
# Create a lock for thread-safe operations
self.lock = threading.Lock()
# Load the initial configuration
self.load_config()
def load_config(self):
# Load the configuration file in a thread-safe manner
with self.lock:
with open(self.config_file, 'r') as f:
self.config_data = json.load(f)
# Print the loaded configuration for debugging
print(""Configuration reloaded:"", self.config_data)
def get_config(self):
# Get the current configuration in a thread-safe manner
with self.lock:
return self.config_data
def start_watching(self):
# Create a file system event handler for the configuration file
event_handler = ConfigFileHandler(self, self.config_file)
# Create an observer to monitor file system changes
observer = Observer()
# Schedule the observer to watch the current directory for changes
observer.schedule(event_handler, path='.', recursive=False)
# Start the observer
observer.start()
print(""Started watching for configuration changes..."")
try:
# Continuously check if the stop event is set
while not stop_event.is_set():
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
# Stop the observer when shutting down
print(""Stopping observer..."")
observer.stop()
observer.join()
print(""Observer stopped."")
# Define the file system event handler class for configuration file changes
class ConfigFileHandler(FileSystemEventHandler):
def __init__(self, config_manager, config_file):
# Initialize with the config manager and the configuration file path
self.config_manager = config_manager
self.config_file = os.path.abspath(config_file)
def on_modified(self, event):
# Check if the modified file is the configuration file
if os.path.abspath(event.src_path) == self.config_file:
# Print the modification event for debugging
print(f""Configuration file {event.src_path} changed, reloading..."")
# Reload the configuration
self.config_manager.load_config()
# Define a signal handler for SIGINT to handle graceful shutdown
def handle_sigint(signal, frame):
global stop_event
print(""Shutting down..."")
# Set the stop event to terminate the program
stop_event.set()
# Example usage
if __name__ == ""__main__"":
# Define the path to the configuration file
config_file = 'config.json'
# Create an instance of ConfigManager with the configuration file
config_manager = ConfigManager(config_file)
# Create an event to signal stopping
stop_event = threading.Event()
# Register the signal handler for SIGINT
signal.signal(signal.SIGINT, handle_sigint)
# Start watching for configuration changes in a separate thread
watcher_thread = threading.Thread(target=config_manager.start_watching)
watcher_thread.start()
# Simulate application usage
try:
while not stop_event.is_set():
# Get and print the current configuration periodically
config = config_manager.get_config()
print(""Current configuration:"", config)
time.sleep(5)
except KeyboardInterrupt:
pass
# Signal the watcher thread to stop
stop_event.set()
# Wait for the watcher thread to finish
watcher_thread.join()
print(""Program terminated."")",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
print(""Add:"", np.add(1.0, 4.0))
print(""Subtract:"", np.subtract(1.0, 4.0))
print(""Multiply:"", np.multiply(1.0, 4.0))
print(""Divide:"", np.divide(1.0, 4.0)) ",1,PERPLEXITY,"Write a NumPy program to add, subtract, multiply, divide arguments element-wise.",PYTHON
,"# Import the random module for generating random numbers
import random
# Import the numpy module for numerical operations
import numpy as np
# Problem definition: Example function to optimize (e.g., Rastrigin function)
def rastrigin(x):
# Define the constant A
A = 10
# Compute the Rastrigin function value for the input x
return A * len(x) + sum([(xi**2 - A * np.cos(2 * np.pi * xi)) for xi in x])
# GA Parameters
# Set the population size
population_size = 100
# Set the genome length (number of genes in a chromosome)
genome_length = 10
# Set the crossover rate
crossover_rate = 0.8
# Set the mutation rate
mutation_rate = 0.01
# Set the number of generations
num_generations = 100
# Define the bounds for the gene values
bounds = [-5.12, 5.12]
# Initialization
def initialize_population(pop_size, genome_len, bounds):
# Generate a population of random individuals within the given bounds
return [np.random.uniform(bounds[0], bounds[1], genome_len) for _ in range(pop_size)]
# Fitness function
def evaluate_fitness(population):
# Evaluate the fitness of each individual in the population using the Rastrigin function
return [rastrigin(individual) for individual in population]
# Selection (Tournament Selection)
def tournament_selection(population, fitness, tournament_size=3):
# Initialize the list of selected individuals
selected = []
# Select individuals based on tournament selection
for _ in range(len(population)):
# Choose random aspirants for the tournament
aspirants = [random.randint(0, len(population) - 1) for _ in range(tournament_size)]
# Select the individual with the best fitness among the aspirants
selected.append(min(aspirants, key=lambda aspirant: fitness[aspirant]))
# Return the selected individuals
return [population[i] for i in selected]
# Crossover (Single Point Crossover)
def single_point_crossover(parent1, parent2):
# Perform crossover with a given probability
if random.random() < crossover_rate:
# Choose a random crossover point
point = random.randint(1, len(parent1) - 1)
# Create children by combining the parents at the crossover point
child1 = np.concatenate([parent1[:point], parent2[point:]])
child2 = np.concatenate([parent2[:point], parent1[point:]])
# Return the children
return child1, child2
# If no crossover, return the parents as is
return parent1, parent2
# Mutation
def mutate(individual, mutation_rate, bounds):
# Mutate each gene with a given probability
for i in range(len(individual)):
if random.random() < mutation_rate:
# Replace the gene with a random value within the bounds
individual[i] = np.random.uniform(bounds[0], bounds[1])
# Return the mutated individual
return individual
# Genetic Algorithm
def genetic_algorithm():
# Initialize the population
population = initialize_population(population_size, genome_length, bounds)
# Iterate over the number of generations
for generation in range(num_generations):
# Evaluate the fitness of the population
fitness = evaluate_fitness(population)
# Selection
# Select individuals based on their fitness
selected_population = tournament_selection(population, fitness)
# Crossover
# Create the next generation through crossover
next_population = []
for i in range(0, len(selected_population), 2):
parent1 = selected_population[i]
parent2 = selected_population[min(i + 1, len(selected_population) - 1)]
child1, child2 = single_point_crossover(parent1, parent2)
next_population.extend([child1, child2])
# Mutation
# Mutate the individuals in the next generation
population = [mutate(individual, mutation_rate, bounds) for individual in next_population]
# Evaluation
# Re-evaluate the fitness of the new population
fitness = evaluate_fitness(population)
# Find the best fitness and corresponding individual
best_fitness = min(fitness)
best_individual = population[fitness.index(best_fitness)]
# Print the best fitness of the current generation
print(f'Generation {generation + 1}: Best Fitness = {best_fitness}')
# Return the best individual found
return best_individual
# Uncomment the line below to run the genetic algorithm
best_solution = genetic_algorithm()
# Print the best solution found
print(""Best solution found:"", best_solution)",0,W3RESOURCE,NA,PYTHON
,"def abc():
x = 1
y = 2
str1 = ""w3resource""
print(""Python Exercises"")
print(abc.__code__.co_nlocals) # Output: 3 ",1,PERPLEXITY,Write a Python program to detect the number of local variables declared in a function.,PYTHON
,"# Define a function that returns the maximum of two numbers
def max_of_two(x, y):
# Check if x is greater than y
if x > y:
# If x is greater, return x
return x
# If y is greater or equal to x, return y
return y
# Define a function that returns the maximum of three numbers
def max_of_three(x, y, z):
# Call max_of_two function to find the maximum of y and z,
# then compare it with x to find the overall maximum
return max_of_two(x, max_of_two(y, z))
# Print the result of calling max_of_three function with arguments 3, 6, and -5
print(max_of_three(3, 6, -5)) ",0,W3RESOURCE,NA,PYTHON
,"def test(a):
def add(b):
nonlocal a
a += 1
return a + b
return add
a = int(input(""Enter value for a: ""))
func = test(a)
b = int(input(""Enter value for b: ""))
print(""Result:"", func(b)) ",1,PERPLEXITY,Write a Python program to access a function inside a function.,PYTHON
,"# Define a function named 'sum' that takes a list of numbers as input
def sum(numbers):
# Initialize a variable 'total' to store the sum of numbers, starting at 0
total = 0
# Iterate through each element 'x' in the 'numbers' list
for x in numbers:
# Add the current element 'x' to the 'total'
total += x
# Return the final sum stored in the 'total' variable
return total
# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)
print(sum((8, 2, 3, 0, 7))) ",0,,NA,PYTHON
,"code = input(""Enter Python code: "")
exec(code) ",1,PERPLEXITY,Write a Python program to execute a string containing Python code,PYTHON
,"# Define a function named 'multiply' that takes a list of numbers as input
def multiply(numbers):
# Initialize a variable 'total' to store the multiplication result, starting at 1
total = 1
# Iterate through each element 'x' in the 'numbers' list
for x in numbers:
# Multiply the current element 'x' with the 'total'
total *= x
# Return the final multiplication result stored in the 'total' variable
return total
# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)
print(multiply((8, 2, 3, -1, 7))) ",0,W3RESOURCE,NA,PYTHON
,"def bold(fn): return lambda: f""<b>{fn()}</b>""
def italic(fn): return lambda: f""<i>{fn()}</i>""
def underline(fn): return lambda: f""<u>{fn()}</u>""
text = input(""Enter text: "")
hello = underline(italic(bold(lambda: text)))
print(hello()) ",1,PERPLEXITY,"Write a Python program to create a chain of function decorators (bold, italic, underline etc.).",PYTHON
,"# Define a function named 'string_reverse' that takes a string 'str1' as input
def string_reverse(str1):
# Initialize an empty string 'rstr1' to store the reversed string
rstr1 = ''
# Calculate the length of the input string 'str1'
index = len(str1)
# Execute a while loop until 'index' becomes 0
while index > 0:
# Concatenate the character at index - 1 of 'str1' to 'rstr1'
rstr1 += str1[index - 1]
# Decrement the 'index' by 1 for the next iteration
index = index - 1
# Return the reversed string stored in 'rstr1'
return rstr1
# Print the result of calling the 'string_reverse' function with the input string '1234abcd'
print(string_reverse('1234abcd'))",0,W3RESOURCE,NA,PYTHON
,"def printValues():
l = [i**2 for i in range(1, 31)]
print(l)
printValues() ",1,PERPLEXITY,"
Write a Python function to create and print a list where the values are the squares of numbers between 1 and 30 (both included).",PYTHON
,"# Define a function named 'factorial' that calculates the factorial of a number 'n'
def factorial(n):
# Check if the number 'n' is 0
if n == 0:
# If 'n' is 0, return 1 (factorial of 0 is 1)
return 1
else:
# If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n'
return n * factorial(n - 1)
# Ask the user to input a number to compute its factorial and store it in variable 'n'
n = int(input(""Input a number to compute the factorial: ""))
# Print the factorial of the number entered by the user by calling the 'factorial' function
print(factorial(n))",0,W3RESOURCE,NA,PYTHON
,"# Input
user_input = input(""Enter hyphen-separated words: "")
# Process
items = [n for n in user_input.split('-')]
items.sort()
result = '-'.join(items)
# Output
print(""Sorted:"", result) ",1,PERPLEXITY,Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.,PYTHON
,"# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive)
def test_range(n):
# Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement
if n in range(3, 9):
# If 'n' is within the range, print that 'n' is within the given range
print(""%s is in the range"" % str(n))
else:
# If 'n' is outside the range, print that the number is outside the given range
print(""The number is outside the given range."")
# Call the 'test_range' function with the argument 5
test_range(5)",0,W3RESOURCE,NA,PYTHON
,"import string
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
str_set = set(str1.lower())
return alphaset <= str_set
# Test
print(ispangram('The quick brown fox jumps over the lazy dog')) # True ",1,PERPLEXITY,Write a Python function to check whether a string is a pangram or not.,PYTHON
,"# Define a function named 'string_test' that counts the number of upper and lower case characters in a string 's'
def string_test(s):
# Create a dictionary 'd' to store the count of upper and lower case characters
d = {""UPPER_CASE"": 0, ""LOWER_CASE"": 0}
# Iterate through each character 'c' in the string 's'
for c in s:
# Check if the character 'c' is in upper case
if c.isupper():
# If 'c' is upper case, increment the count of upper case characters in the dictionary
d[""UPPER_CASE""] += 1
# Check if the character 'c' is in lower case
elif c.islower():
# If 'c' is lower case, increment the count of lower case characters in the dictionary
d[""LOWER_CASE""] += 1
else:
# If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing
pass
# Print the original string 's'
print(""Original String: "", s)
# Print the count of upper case characters
print(""No. of Upper case characters: "", d[""UPPER_CASE""])
# Print the count of lower case characters
print(""No. of Lower case Characters: "", d[""LOWER_CASE""])
# Call the 'string_test' function with the input string 'The quick Brown Fox'
string_test('The quick Brown Fox')",0,W3RESOURCE,NA,PYTHON
,"def pascal_triangle(n):
for i in range(n):
row = [1]
for j in range(1, i):
row.append(row[j-1] + row[j])
row.append(1) if i > 0 else None
print(row)
# Test
pascal_triangle(6) ",1,PERPLEXITY,Write a Python function that prints out the first n rows of Pascal's triangle.,PYTHON
,"# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements
def unique_list(l):
# Create an empty list 'x' to store unique elements
x = []
# Iterate through each element 'a' in the input list 'l'
for a in l:
# Check if the element 'a' is not already present in the list 'x'
if a not in x:
# If 'a' is not in 'x', add it to the list 'x'
x.append(a)
# Return the list 'x' containing unique elements
return x
# Print the result of calling the 'unique_list' function with a list containing duplicate elements
print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) ",0,W3RESOURCE,NA,PYTHON
,"def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if string[left_pos] != string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
# Test
print(isPalindrome('aza')) # True ",1,PERPLEXITY,Write a Python function that checks whether a passed string is a palindrome or not.,PYTHON
,"# Define a function named 'test_prime' that checks if a number 'n' is a prime number
def test_prime(n):
# Check if 'n' is equal to 1
if (n == 1):
# If 'n' is 1, return False (1 is not a prime number)
return False
# Check if 'n' is equal to 2
elif (n == 2):
# If 'n' is 2, return True (2 is a prime number)
return True
else:
# Iterate through numbers from 2 to (n-1) using 'x' as the iterator
for x in range(2, n):
# Check if 'n' is divisible by 'x' without any remainder
if (n % x == 0):
# If 'n' is divisible by 'x', return False (not a prime number)
return False
# If 'n' is not divisible by any number from 2 to (n-1), return True (prime number)
return True
# Print the result of checking if 9 is a prime number by calling the 'test_prime' function
print(test_prime(9))",0,W3RESOURCE,NA,PYTHON
,"def perfect_number(n):
sum_div = 0
for x in range(1, n):
if n % x == 0:
sum_div += x
return sum_div == n
# Test
print(perfect_number(6)) # True (1+2+3=6) ",1,PERPLEXITY,"Write a Python function to check whether a number is ""Perfect"" or not.",PYTHON
,"# Define a function named 'is_even_num' that takes a list 'l' as input and returns a list of even numbers
def is_even_num(l):
# Create an empty list 'enum' to store even numbers
enum = []
# Iterate through each number 'n' in the input list 'l'
for n in l:
# Check if the number 'n' is even (divisible by 2 without a remainder)
if n % 2 == 0:
# If 'n' is even, append it to the 'enum' list
enum.append(n)
# Return the list 'enum' containing even numbers
return enum
# Print the result of calling the 'is_even_num' function with a list of numbers
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",0,W3RESOURCE,NA,PYTHON
,"def is_even_num(l):
return [n for n in l if n % 2 == 0]
# Example usage
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",1,PERPLEXITY,Write a Python program to print the even numbers from a given list.,PYTHON
,"# Define a function named 'perfect_number' that checks if a number 'n' is a perfect number
def perfect_number(n):
# Initialize a variable 'sum' to store the sum of factors of 'n'
sum = 0
# Iterate through numbers from 1 to 'n-1' using 'x' as the iterator
for x in range(1, n):
# Check if 'x' is a factor of 'n' (divides 'n' without remainder)
if n % x == 0:
# If 'x' is a factor of 'n', add it to the 'sum'
sum += x
# Check if the 'sum' of factors is equal to the original number 'n'
return sum == n
# Print the result of checking if 6 is a perfect number by calling the 'perfect_number' function
print(perfect_number(6))",0,W3RESOURCE,NA,PYTHON
,"def test_prime(n):
if n <= 1:
return False
for x in range(2, n):
if n % x == 0:
return False
return True
# Accepts input from user
n = int(input(""Enter a number: ""))
print(test_prime(n)) ",1,PERPLEXITY,"Write a Python function that takes a number as a parameter and checks whether the number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself.",PYTHON
,"# Define a function named 'isPalindrome' that checks if a string is a palindrome
def isPalindrome(string):
# Initialize left and right pointers to check characters from the start and end of the string
left_pos = 0
right_pos = len(string) - 1
# Loop until the pointers meet or cross each other
while right_pos >= left_pos:
# Check if the characters at the left and right positions are not equal
if not string[left_pos] == string[right_pos]:
# If characters don't match, return False (not a palindrome)
return False
# Move the left pointer to the right and the right pointer to the left to continue checking
left_pos += 1
right_pos -= 1
# If the loop finishes without returning False, the string is a palindrome, so return True
return True
# Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function
print(isPalindrome('aza')) ",0,W3RESOURCE,NA,PYTHON
,"def unique_list(l):
return list(set(l))
# Example usage
print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) ",1,PERPLEXITY,Write a Python function that takes a list and returns a new list with distinct elements from the first list.,PYTHON
,"# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n'
def pascal_triangle(n):
# Initialize the first row of Pascal's Triangle with value 1 as a starting point
trow = [1]
# Create a list 'y' filled with zeros to be used for calculations
y = [0]
# Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n')
for x in range(max(n, 0)):
# Print the current row of Pascal's Triangle
print(trow)
# Update the current row based on the previous row by calculating the next row using list comprehension
# The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements
trow = [l + r for l, r in zip(trow + y, y + trow)]
# Return True if 'n' is greater than or equal to 1, else return False
return n >= 1
# Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function
pascal_triangle(6) ",0,W3RESOURCE,NA,PYTHON
,"def string_test(s):
upper_count = 0
lower_count = 0
for ch in s:
if ch.isupper():
upper_count += 1
elif ch.islower():
lower_count += 1
print(""No. of Upper case characters :"", upper_count)
print(""No. of Lower case Characters :"", lower_count)
# Example usage
string_test('The quick Brow Fox') ",1,PERPLEXITY,"Write a Python function that accepts a string and counts the number of upper and lower case letters.
Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12",PYTHON
,"# Import the 'string' and 'sys' modules
import string
import sys
# Define a function named 'ispangram' that checks if a string is a pangram
def ispangram(str1, alphabet=string.ascii_lowercase):
# Create a set 'alphaset' containing all lowercase letters from the provided alphabet
alphaset = set(alphabet)
# Convert the input string to lowercase and create a set from it
str_set = set(str1.lower())
# Check if the set of lowercase characters in the input string covers all characters in 'alphaset'
return alphaset <= str_set
# Print the result of checking if the string is a pangram by calling the 'ispangram' function
print(ispangram('The quick brown fox jumps over the lazy dog'))
",0,W3RESOURCE,NA,PYTHON
,"def in_range(n, low, high):
return low <= n <= high
# ---------- INPUT ----------
n, low, high = 5, 3, 8
# ---------- OUTPUT ----------
if in_range(n, low, high):
print(f""{n} is in the range {low} to {high}"")
else:
print(f""{n} is outside the range {low} to {high}"") ",1,GPT,Write a Python function to check whether a number falls within a given range.,PYTHON
,"# Take user input and split it into a list based on the hyphen (""-"") separator, creating a list named 'items'
items = [n for n in input().split('-')]
# Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting)
items.sort()
# Join the sorted elements in the 'items' list using the hyphen (""-"") separator and print the resulting string
print('-'.join(items)) ",0,W3RESOURCE,NA,PYTHON
,"def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
# General usage
print(factorial(6)) # Output: 720
",1,PERPLEXITY,Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.,PYTHON
,"# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
def printValues():
# Create an empty list 'l'
l = list()
# Iterate through numbers from 1 to 20 (inclusive)
for i in range(1, 21):
# Calculate the square of 'i' and append it to the list 'l'
l.append(i**2)
# Print the list containing squares of numbers from 1 to 20
print(l)
# Call the 'printValues' function to generate and print the list of squares
printValues() ",0,W3RESOURCE,NA,PYTHON
,"def string_reverse(text):
return text[::-1]
# General usage
input_string = ""python""
print(string_reverse(input_string)) # Output: ""nohtyp"" ",1,PERPLEXITY,"Write a Python program to reverse a string.
Sample String : ""1234abcd""
Expected Output : ""dcba4321"" dont give the code for this particular samples , give it in a general way of i/o",PYTHON
,"# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value
def make_bold(fn):
def wrapped():
return ""<b>"" + fn() + ""</b>""
return wrapped
# Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value
def make_italic(fn):
def wrapped():
return ""<i>"" + fn() + ""</i>""
return wrapped
# Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value
def make_underline(fn):
def wrapped():
return ""<u>"" + fn() + ""</u>""
return wrapped
# Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function
@make_bold
@make_italic
@make_underline
def hello():
return ""hello world""
# Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline
print(hello()) ## returns ""<b><i><u>hello world</u></i></b>""",0,W3RESOURCE,NA,PYTHON
,"def multiply_numbers(numbers):
return 1 if not numbers else numbers[0] * multiply_numbers(numbers[1:])
# Or using reduce (from functools)
from functools import reduce
def multiply_numbers(numbers):
return reduce(lambda x, y: x * y, numbers, 1)
print(multiply_numbers([8, 2, 3, -1, 7])) # Output: -336 ",1,PERPLEXITY,"Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7)
Expected Output : -336",PYTHON
,"# Define a string variable 'mycode' containing a Python code as a string
mycode = 'print(""hello world"")'
# Define a multi-line string variable 'code' containing Python code as a string
code = """"""
def mutiply(x,y):
return x*y
print('Multiply of 2 and 3 is: ',mutiply(2,3))
""""""
# Execute the Python code represented by the string stored in the variable 'mycode'
exec(mycode)
# Execute the Python code represented by the multi-line string stored in the variable 'code'
exec(code) ",0,W3RESOURCE,NA,PYTHON
,"def sum_numbers(numbers):
return sum(numbers)
print(sum_numbers([8, 2, 3, 0, 7])) # Output: 20 ",1,PERPLEXITY,"Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20",PYTHON
,"# Define a function named 'test' that takes a parameter 'a'
def test(a):
# Define a nested function 'add' that takes a parameter 'b'
def add(b):
# Declare 'a' from the outer scope as nonlocal to modify its value
nonlocal a
# Increment the value of 'a' by 1
a += 1
# Return the sum of 'a' (modified by the nonlocal statement) and 'b'
return a + b
# Return the inner function 'add' and its scope is retained due to closure
return add
# Call the 'test' function with an argument '4' and assign the returned function to 'func'
func = test(4)
# Call the function 'func' with argument '4' and print the result
print(func(4)) ",0,W3RESOURCE,NA,PYTHON
,"def max_of_three(a, b, c):
return max(a, b, c)
# ---------- INPUT ----------
x, y, z = 3, 6, -5
# ---------- OUTPUT ----------
print(""Maximum:"", max_of_three(x, y, z))
",1,GPT,Write a Python function to find the maximum of three numbers.,PYTHON
,"# Define a function named 'abc'
def abc():
# Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc'
x = 1
y = 2
str1 = ""w3resource""
# Print the string ""Python Exercises""
print(""Python Exercises"")
# Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute
print(abc.__code__.co_nlocals) ",0,W3RESOURCE,NA,PYTHON
,"import random, numpy as np
f = lambda x: 10*len(x) + sum(x*x - 10*np.cos(2*np.pi*x))
def GA(pop=50, n=5, gen=50):
P = [np.random.uniform(-5,5,n) for _ in range(pop)]
for g in range(gen):
P = sorted(P, key=f)
print(f""Gen {g+1} Best:"", f(P[0]))
N = P[:10]
while len(N)<pop:
a,b = random.sample(P[:20],2)
p = random.randint(1,n-1)
c = np.r_[a[:p], b[p:]]
c += np.random.uniform(-0.1,0.1,n)*(np.random.rand(n)<0.1)
N.append(c)
P = N
return P[0] ",1,GPT,Write AN EFFECTIVE SHORTEST LINE OF Python program to implement a genetic algorithm for solving optimization problems.,PYTHON
,"# Importing the NumPy library
import numpy as np
# Displaying a message for addition operation
print(""Add:"")
# Performing addition
print(np.add(1.0, 4.0))
# Displaying a message for subtraction operation
print(""Subtract:"")
# Performing subtraction
print(np.subtract(1.0, 4.0))
# Displaying a message for multiplication operation
print(""Multiply:"")
# Performing multiplication
print(np.multiply(1.0, 4.0))
# Displaying a message for division operation
print(""Divide:"")
# Performing division
print(np.divide(1.0, 4.0))",0,W3RESOURCE,NA,PYTHON
,"import json, threading, time, signal, os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Config:
def __init__(s,f):
s.f, s.d, s.l = f, {}, threading.Lock()
s.load()
def load(s):
with s.l: s.d = json.load(open(s.f))
print(""Reloaded:"", s.d)
def get(s):
with s.l: return s.d
class Watch(FileSystemEventHandler):
def __init__(s,c): s.c, s.p = c, os.path.abspath(c.f)
def on_modified(s,e):
if os.path.abspath(e.src_path)==s.p: s.c.load()
# ---------- INPUT ----------
CFG_FILE = ""config.json""
cfg = Config(CFG_FILE)
stop = threading.Event()
def shutdown(sig, frm): stop.set()
signal.signal(signal.SIGINT, shutdown)
obs = Observer()
obs.schedule(Watch(cfg), ""."", False)
obs.start()
# ---------- OUTPUT ----------
try:
while not stop.is_set():
print(""Current:"", cfg.get())
time.sleep(3)
finally:
obs.stop(); obs.join()
print(""Stopped"") ",1,GPT,Write a Python program to create a dynamic configuration manager that reloads settings at runtime. MAKE THE CODE MORE SHORTER AND EFFECTIVE TO PASS ALL THE TEST CASES,PYTHON
,"# Importing the NumPy library
import numpy as np
# Calculating the natural logarithm of 1e-50 and 2.5e-50
l1 = np.log(1e-50)
l2 = np.log(2.5e-50)
# Displaying the logarithm of the sum of exponentiations
print(""Logarithm of the sum of exponentiations:"")
print(np.logaddexp(l1, l2))
# Displaying the logarithm of the sum of exponentiations of the inputs in base-2
print(""Logarithm of the sum of exponentiations of the inputs in base-2:"")
print(np.logaddexp2(l1, l2))
",0,W3RESOURCE,NA,PYTHON
,"import ast, math
SAFE = {k:v for k,v in vars(math).items() if not k.startswith(""_"")}
def evaluate(expr):
try:
return eval(compile(ast.parse(expr, ""eval""), """", ""eval""), {}, SAFE)
except Exception as e:
return f""Error: {e}""
# ---------- USER INPUT ----------
expr = input(""Enter math expression: "")
# ---------- OUTPUT ----------
print(""Result:"", evaluate(expr)) ",1,GPT,"# Import the Abstract Syntax Tree (AST) module
import ast
# Import the math module for mathematical functions and constants
import math
# Define a class for evaluating mathematical expressions
class MathExpressionEvaluator:
def __init__(self):
pass
# Method to evaluate mathematical expressions
def evaluate(self, expression):
try:
# Parse the expression into an Abstract Syntax Tree (AST)
parsed_expression = ast.parse(expression, mode='eval')
# Define the allowed names (functions and constants) for evaluation
allowed_names = {
'sin': math.sin,
'cos': math.cos,
'tan': math.tan,
'log': math.log,
'sqrt': math.sqrt,
**vars(math) # Include all functions and constants from the math module
}
# Evaluate the AST using a custom namespace that includes the allowed names
result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names)
return result
except SyntaxError:
print(""Invalid expression syntax."")
return None
except Exception as e:
print(""Error:"", e)
return None
# Example usage
if __name__ == ""__main__"":
evaluator = MathExpressionEvaluator()
# Evaluate mathematical expressions
print(""Evaluation Results:"")
print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4""))
print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4""))
print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)""))
print(""log(10) ="", evaluator.evaluate(""log(10)""))
Write a Python library for parsing and evaluating mathematical expressions., THE ABOVE code is the solution i got from one of the websites make this shorter and give me the effective one with a feature of user entering the inputs ",PYTHON
,"# Importing the NumPy library
import numpy as np
# Creating an array from 0 to 9
x = np.arange(10)
# Displaying the original array
print(""Original array:"")
print(x)
# Performing element-wise division of the array by 3 using true_divide function
print(""Division of the array inputs, element-wise:"")
print(np.true_divide(x, 3)) ",0,W3RESOURCE,NA,PYTHON
,"from collections import OrderedDict
class LRUCache:
def __init__(self, cap):
self.cap, self.d = cap, OrderedDict()
def get(self, k):
if k not in self.d: return -1
self.d.move_to_end(k)
return self.d[k]
def put(self, k, v):
if k in self.d: self.d.move_to_end(k)
self.d[k] = v
if len(self.d) > self.cap:
self.d.popitem(last=False) ",1,GPT,Write a Python program to create a caching system with support for LRU eviction policy TO PASS ALL THE TEST CASES,PYTHON
,"import numpy as np
x = [1., 2., 3., 4.]
print(""Original array:"")
print(x)
print(""Largest integer smaller or equal to the division of the inputs:"")
print(np.floor_divide(x, 1.5))
",0,W3RESOURCE,NA,PYTHON
,"import asyncio
class Scheduler:
def __init__(self): self.tasks=[]
def add(self, coro, *args): self.tasks.append(coro(*args))
async def run(self): await asyncio.gather(*self.tasks)
async def task(name, t):
print(f""Task {name} started ({t}s)"")
await asyncio.sleep(t)
print(f""Task {name} finished"")
# ---------- INPUT ----------
async def main():
s = Scheduler()
s.add(task, ""A"", 2)
s.add(task, ""B"", 1)
s.add(task, ""C"", 3)
await s.run()
# ---------- OUTPUT ----------
asyncio.run(main())
",1,GPT,Write a Python program that builds a concurrent task scheduler using asyncio WITH I/O,PYTHON
,"# Importing the NumPy library
import numpy as np
# Creating an array from 0 to 6
x = np.arange(7)
# Displaying the original array
print(""Original array:"")
print(x)
# Raising the elements of the array to the power of 3 and displaying the result
print(""First array elements raised to powers from second array, element-wise:"")
print(np.power(x, 3)) ",0,W3RESOURCE,NA,PYTHON
,"import hashlib
class Bloom:
def __init__(s,n,k):
s.n,s.k,s.b=n,k,[0]*n
def _h(s,x):
h1=int(hashlib.sha256(x.encode()).hexdigest(),16)
h2=int(hashlib.md5(x.encode()).hexdigest(),16)
return [(h1+i*h2)%s.n for i in range(s.k)]
def add(s,x):
for i in s._h(x): s.b[i]=1
def check(s,x):
return all(s.b[i] for i in s._h(x))
",1,GPT,"WRITE THE PYTHON CODE FOR Bloom Filter Implementation with i/o , let the code you provide be efficient and accurate for the results it provide",PYTHON
,"def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))",0,W3RESOURCE,NA,PYTHON
,"import json
class Address:
def __init__(s,st,ct,stt,z): s.street, s.city, s.state, s.zip = st,ct,stt,z
class Person:
def __init__(s,n,a,ad): s.name, s.age, s.address = n,a,ad
class Encoder(json.JSONEncoder):
def default(s,o):
if hasattr(o,""__dict__""):
return {""__t__"":o.__class__.__name__, **o.__dict__}
return super().default(o)
def decoder(d):
if ""__t__"" in d:
cls = {""Address"":Address,""Person"":Person}[d.pop(""__t__"")]
return cls(**d)
return d ",1,GPT,GIVE me a python code for Custom JSON Encoder/Decoder,PYTHON
,"def Sequential_Search(dlist, item):
pos = 0
found = False
while pos < len(dlist) and not found:
if dlist[pos] == item:
found = True
else:
pos = pos + 1
return found, pos
print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))",0,W3RESOURCE,NA,PYTHON
,"import os, shutil, argparse
def sync(src, dst):
if not os.path.isdir(src) or not os.path.isdir(dst):
print(""Invalid source or destination""); return
for r,_,fs in os.walk(src):
d = os.path.join(dst, os.path.relpath(r, src))
os.makedirs(d, exist_ok=True)
for f in fs:
shutil.copy2(os.path.join(r,f), os.path.join(d,f))
if __name__ == ""__main__"":
p = argparse.ArgumentParser()
p.add_argument(""src""); p.add_argument(""dst"")
a = p.parse_args()
sync(a.src, a.dst)
print(""Sync complete"") ",1,GPT,"GIVE ME A python CODE FOR Command-Line File Synchronizer , make it more shorter for effective to pass all the testcases",PYTHON
,"def Ordered_binary_Search(olist, item):
if len(olist) == 0:
return False
else:
midpoint = len(olist) // 2
if olist[midpoint] == item:
return True
else:
if item < olist[midpoint]:
return binarySearch(olist[:midpoint], item)
else:
return binarySearch(olist[midpoint+1:], item)
def binarySearch(alist, item):
first = 0
last = len(alist) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if alist[midpoint] == item:
found = True
else:
if item < alist[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3))
print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17))",0,W3RESOURCE,NA,PYTHON
,"import heapq
def astar(start, goal, g, h):
pq = [(h(start), 0, start, [start])]
seen = set()
while pq:
f,c,u,p = heapq.heappop(pq)
if u == goal: return p, c
if u in seen: continue
seen.add(u)
for v,w in g[u]:
heapq.heappush(pq,(c+w+h(v), c+w, v, p+[v]))
# ---------- INPUT ----------
graph = {
'A':[('B',1),('C',3)],
'B':[('D',1),('E',4)],
'C':[('F',5)],
'D':[('G',1)],
'E':[('G',1)],
'F':[('G',1)],
'G':[]
}
heuristic = {'A':5,'B':4,'C':4,'D':2,'E':2,'F':3,'G':0}
path, cost = astar('A','G',graph,lambda n: heuristic[n])
# ---------- OUTPUT ----------
print(""Path:"", path)
print(""Cost:"", cost) ",1,GPT,give me the code for A* Search Algorithm in shorter lines to implement it with i/o,PYTHON
,"def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
nlist = [14,46,43,27,57,41,45,21,70]
bubbleSort(nlist)
print(nlist)",0,W3RESOURCE,NA,PYTHON
,"from dataclasses import dataclass, field, fields
class ValidationError(Exception): pass
def vfield(d=None, v=()):
return field(default=d, metadata={""v"": v})
def validate(o):
for f in fields(o):
for fn in f.metadata.get(""v"", ()):
if not fn(getattr(o, f.name)):
raise ValidationError(f""{f.name} invalid"")
@dataclass
class User:
name: str
age: int = vfield(0, v=[lambda x: 0 <= x <= 150])
email: str = vfield("""", v=[lambda x: ""@"" in x])
# ---------- INPUT ----------
u = User(""Arsen"", 30, ""arsen@example.com"")
# ---------- OUTPUT ----------
try:
validate(u)
print(""User is valid"")
except ValidationError as e:
print(e)
",1,GPT,write a shorter python code for Data Validation Library with Dataclasses including I/O,PYTHON
,"def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist) ",0,W3RESOURCE,NA,PYTHON
,"from queue import PriorityQueue
from threading import Thread
q = PriorityQueue()
def producer():
for _ in range(int(input(""Items: ""))):
x,p = map(int,input(""item priority: "").split())
q.put((p,x))
q.put((None,None))
def consumer():
while (p,x := q.get()) != (None,None):
print(""Consumed:"", x)
Thread(target=producer).start()
Thread(target=consumer).start() ",1,GPT,"# Import the queue module to use PriorityQueue import queue # Import the threading module to use threads and locks import threading # Define a class for a thread-safe priority queue class ThreadSafePriorityQueue: def __init__(self): # Initialize a PriorityQueue object to hold the items self._queue = queue.PriorityQueue() # Initialize a lock to ensure thread safety self._lock = threading.Lock() # Method to put an item into the priority queue def put(self, item, priority): # Acquire the lock to ensure thread safety with self._lock: # Put the item into the queue with its priority self._queue.put((priority, item)) # Method to get an item from the priority queue def get(self): # Acquire the lock to ensure thread safety with self._lock: # Check if the queue is not empty if not self._queue.empty(): # Get the item with the highest priority (lowest priority number) priority, item = self._queue.get() # Return the item return item else: # Return None if the queue is empty return None # Example usage to demonstrate the thread-safe priority queue if __name__ == ""__main__"": # Define a producer function to add items to the queue def producer(q): # Add 5 items to the queue with their priority as their value for i in range(5): q.put(i, i) # Define a consumer function to get items from the queue def consumer(q): # Continuously get items from the queue while True: # Get an item from the queue item = q.get() # If the item is None, break the loop (end of processing) if item is None: break # Print the consumed item print(""Consumed:"", item) # Create an instance of the thread-safe priority queue q = ThreadSafePriorityQueue() # Create a producer thread to add items to the queue producer_thread = threading.Thread(target=producer, args=(q,)) # Create a consumer thread to get items from the queue consumer_thread = threading.Thread(target=consumer, args=(q,)) # Start the producer thread producer_thread.start() # Start the consumer thread consumer_thread.start() # Wait for the producer thread to finish producer_thread.join() # Add a sentinel value to the queue to signal the consumer to stop q.put(None, None) # Wait for the consumer thread to finish consumer_thread.join() refer this code and give me the shorter version of this code with minimal lines to implement it efficiently",PYTHON
,"def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)",0,W3RESOURCE,NA,PYTHON
,"def matmul(A, B):
return [[sum(a*b for a,b in zip(r,c)) for c in zip(*B)] for r in A]
r1,c1 = map(int,input(""A rows cols: "").split())
A = [list(map(int,input().split())) for _ in range(r1)]
r2,c2 = map(int,input(""B rows cols: "").split())
B = [list(map(int,input().split())) for _ in range(r2)]
print(matmul(A,B))
",1,GPT,give me a pythoncode for Matrix Multiplication via List Comprehensions also add a way to give input and get the result of the matrix multiplication within a shorter lines of code,PYTHON
,"def shellSort(alist):
sublistcount = len(alist)//2
while sublistcount > 0:
for start_position in range(sublistcount):
gap_InsertionSort(alist, start_position, sublistcount)
print(""After increments of size"",sublistcount, ""The list is"",nlist)
sublistcount = sublistcount // 2
def gap_InsertionSort(nlist,start,gap):
for i in range(start+gap,len(nlist),gap):
current_value = nlist[i]
position = i
while position>=gap and nlist[position-gap]>current_value:
nlist[position]=nlist[position-gap]
position = position-gap
nlist[position]=current_value
nlist = [14,46,43,27,57,41,45,21,70]
shellSort(nlist)
print(nlist) ",0,W3RESOURCE,NA,PYTHON
,"class Node:
def __init__(self, v, kids=None):
self.v, self.kids = v, kids or []
def __iter__(self):
stack = [self]
while stack:
n = stack.pop()
yield n.v
stack.extend(reversed(n.kids)) ",1,GPT,give me the shorter lines of python code for Custom Tree Iterator,PYTHON
,"def mergeSort(nlist):
print(""Splitting "",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print(""Merging "",nlist)
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist) ",0,W3RESOURCE,NA,PYTHON
,"import time
class Timer:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
return lambda *a, **k: self(obj, *a, **k)
def __call__(self, obj, *a, **k):
t = time.time()
r = self.func(obj, *a, **k)
print(f""{self.func.__name__}: {time.time()-t:.4f}s"")
return r
",1,GPT,"write a python code for Class-Based Decorator for Execution Time , let the code be more shorter .",PYTHON
,"def quickSort(data_list):
quickSortHlp(data_list,0,len(data_list)-1)
def quickSortHlp(data_list,first,last):
if first < last:
splitpoint = partition(data_list,first,last)
quickSortHlp(data_list,first,splitpoint-1)
quickSortHlp(data_list,splitpoint+1,last)
def partition(data_list,first,last):
pivotvalue = data_list[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = data_list[leftmark]
data_list[leftmark] = data_list[rightmark]
data_list[rightmark] = temp
temp = data_list[first]
data_list[first] = data_list[rightmark]
data_list[rightmark] = temp
return rightmark
data_list = [54,26,93,17,77,31,44,55,20]
quickSort(data_list)
print(data_list)",0,W3RESOURCE,NA,PYTHON
,"import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin
def fetch(url):
try:
return BeautifulSoup(requests.get(url, timeout=5).text, ""html.parser"")
except:
return None
def scrape(urls, workers=10):
with ThreadPoolExecutor(workers) as t:
return [s for s in t.map(fetch, urls) if s]
start = ""https://example.com""
soup = fetch(start)
links = {urljoin(start, a[""href""]) for a in soup.select(""a[href]"")}
pages = scrape(links)
for p in pages:
print(p.title.string if p.title else ""No title"") ",1,GPT,give me the python3 code for multithread webscrapper in an more efficient way with shorter lines of code to implement ,PYTHON
,"def counting_sort(array1, max_val):
m = max_val + 1
count = [0] * m
for a in array1:
# count occurences
count[a] += 1
i = 0
for a in range(m):
for c in range(count[a]):
array1[i] = a
i += 1
return array1
print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))",0,GFG,NA,PYTHON
,"def maxProfit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
",1,GPT,"You are given an array prices where prices[i] is the price of a stock on day i.
You may choose one day to buy and a later day to sell.
Return the maximum profit you can achieve. If no profit is possible, return 0.
Provide:
- An optimal O(n) solution
- Explanation of the approach
- Python implementation",PYTHON
,"class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxP = 0
minBuy = prices[0]
for sell in prices:
maxP = max(maxP, sell - minBuy)
minBuy = min(minBuy, sell)
return maxP",0,GFG,NA,PYTHON
,"from collections import Counter
def topKFrequent(nums, k):
count = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
buckets[freq].append(num)
res = []
for i in range(len(buckets) - 1, 0, -1):
for num in buckets[i]:
res.append(num)
if len(res) == k:
return res
",1,GPT,"Given an integer array nums and an integer k, return the k most frequent elements.
The solution must be better than O(n log n).
Provide:
- Optimal approach
- Python code using efficient data structures",PYTHON
,"class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
freq = [[] for i in range(len(nums) + 1)]
for num in nums:
count[num] = 1 + count.get(num, 0)
for num, cnt in count.items():
freq[cnt].append(num)
res = []
for i in range(len(freq) - 1, 0, -1):
for num in freq[i]:
res.append(num)
if len(res) == k:
return res",0,GFG,NA,PYTHON
,"def longestConsecutive(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
length = 1
while num + length in num_set:
length += 1
longest = max(longest, length)
return longest
",1,GPT,"Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
The solution must run in O(n) time.",PYTHON
,"class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
mp = defaultdict(int)
res = 0
for num in nums:
if not mp[num]:
mp[num] = mp[num - 1] + mp[num + 1] + 1
mp[num - mp[num - 1]] = mp[num]
mp[num + mp[num + 1]] = mp[num]
res = max(res, mp[num])
return res",0,GFG,NA,PYTHON
,"def twoSum(numbers, target):
l, r = 0, len(numbers) - 1
while l < r:
s = numbers[l] + numbers[r]
if s == target:
return [l + 1, r + 1]
elif s < target:
l += 1
else:
r -= 1
",1,GPT,"Given a sorted array of integers and a target,
return the 1-based indices of the two numbers such that they add up to the target.
Use only constant extra space.",PYTHON
,"class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l, r = 0, len(numbers) - 1
while l < r:
curSum = numbers[l] + numbers[r]
if curSum > target:
r -= 1
elif curSum < target:
l += 1
else:
return [l + 1, r + 1]
return []",0,GFG,NA,PYTHON
,"def maxArea(height):
l, r = 0, len(height) - 1
res = 0
while l < r:
res = max(res, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return res
",1,GPT,"Given an array height, find two lines that together with the x-axis form a container,
such that the container contains the most water.",PYTHON
,"class Solution:
def maxArea(self, heights: List[int]) -> int:
l, r = 0, len(heights) - 1
res = 0
while l < r:
area = min(heights[l], heights[r]) * (r - l)
res = max(res, area)
if heights[l] <= heights[r]:
l += 1
else:
r -= 1
return res",0,GFG,NA,PYTHON
,"def trap(height):
l, r = 0, len(height) - 1
left_max = right_max = 0
res = 0
while l < r:
if height[l] < height[r]:
left_max = max(left_max, height[l])
res += left_max - height[l]
l += 1
else:
right_max = max(right_max, height[r])
res += right_max - height[r]
r -= 1
return res
",1,GPT,"Given an array height representing elevation map,
compute how much water it can trap after raining.",PYTHON
,"class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0
while l < r:
if leftMax < rightMax:
l += 1
leftMax = max(leftMax, height[l])
res += leftMax - height[l]
else:
r -= 1
rightMax = max(rightMax, height[r])
res += rightMax - height[r]
return res",0,GFG,NA,PYTHON
,"from collections import Counter
def checkInclusion(s1, s2):
if len(s1) > len(s2):
return False
s1_count = Counter(s1)
window = Counter(s2[:len(s1)])
if s1_count == window:
return True
for i in range(len(s1), len(s2)):
window[s2[i]] += 1
window[s2[i - len(s1)]] -= 1
if window[s2[i - len(s1)]] == 0:
del window[s2[i - len(s1)]]
if window == s1_count:
return True
return False
",1,GPT,"Given two strings s1 and s2, return true if s2 contains a permutation of s1.
Use a sliding window approach.",PYTHON
,"class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
s1Count, s2Count = [0] * 26, [0] * 26
for i in range(len(s1)):
s1Count[ord(s1[i]) - ord('a')] += 1
s2Count[ord(s2[i]) - ord('a')] += 1
matches = 0
for i in range(26):
matches += (1 if s1Count[i] == s2Count[i] else 0)
l = 0
for r in range(len(s1), len(s2)):
if matches == 26:
return True
index = ord(s2[r]) - ord('a')
s2Count[index] += 1
if s1Count[index] == s2Count[index]:
matches += 1
elif s1Count[index] + 1 == s2Count[index]:
matches -= 1
index = ord(s2[l]) - ord('a')
s2Count[index] -= 1
if s1Count[index] == s2Count[index]:
matches += 1
elif s1Count[index] - 1 == s2Count[index]:
matches -= 1
l += 1
return matches == 26",0,GFG,NA,PYTHON
,"from collections import Counter
def minWindow(s, t):
if not t or not s:
return """"
t_count = Counter(t)
window = {}
have, need = 0, len(t_count)
res, res_len = [-1, -1], float('inf')
l = 0
for r in range(len(s)):
c = s[r]
window[c] = window.get(c, 0) + 1
if c in t_count and window[c] == t_count[c]:
have += 1
while have == need:
if (r - l + 1) < res_len:
res = [l, r]
res_len = r - l + 1
window[s[l]] -= 1
if s[l] in t_count and window[s[l]] < t_count[s[l]]:
have -= 1
l += 1
l, r = res
return s[l:r+1] if res_len != float('inf') else """"
",1,GPT,"Given strings s and t, return the minimum window in s which contains all characters of t.
If no such window exists, return an empty string.",PYTHON
,"class Solution:
def minWindow(self, s: str, t: str) -> str:
if t == """":
return """"
countT, window = {}, {}
for c in t:
countT[c] = 1 + countT.get(c, 0)
have, need = 0, len(countT)
res, resLen = [-1, -1], float(""infinity"")
l = 0
for r in range(len(s)):
c = s[r]
window[c] = 1 + window.get(c, 0)
if c in countT and window[c] == countT[c]:
have += 1
while have == need:
if (r - l + 1) < resLen:
res = [l, r]
resLen = r - l + 1
window[s[l]] -= 1
if s[l] in countT and window[s[l]] < countT[s[l]]:
have -= 1
l += 1
l, r = res
return s[l : r + 1] if resLen != float(""infinity"") else """"",0,GFG,NA,PYTHON
,"def dailyTemperatures(temperatures):
res = [0] * len(temperatures)
stack = []
for i, temp in enumerate(temperatures):
while stack and temp > stack[-1][0]:
stack_temp, idx = stack.pop()
res[idx] = i - idx
stack.append((temp, i))
return res
",1,GPT,"Given an array temperatures, return an array such that each index shows
how many days until a warmer temperature.
Use a monotonic stack.",PYTHON
,"class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
res = [0] * n
for i in range(n - 2, -1, -1):
j = i + 1
while j < n and temperatures[j] <= temperatures[i]:
if res[j] == 0:
j = n
break
j += res[j]
if j < n:
res[i] = j - i
return res",0,GFG,NA,PYTHON
,"def carFleet(target, position, speed):
cars = sorted(zip(position, speed), reverse=True)
stack = []
for pos, spd in cars:
time = (target - pos) / spd
if not stack or time > stack[-1]:
stack.append(time)
return len(stack)
",1,GPT,"Given target, position, and speed arrays,
return the number of car fleets that will arrive at the destination.",PYTHON
,"class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
pair = [(p, s) for p, s in zip(position, speed)]
pair.sort(reverse=True)
fleets = 1
prevTime = (target - pair[0][0]) / pair[0][1]
for i in range(1, len(pair)):
currCar = pair[i]
currTime = (target - currCar[0]) / currCar[1]
if currTime > prevTime:
fleets += 1
prevTime = currTime
return fleets",0,GFG,NA,PYTHON
,"import math
def minEatingSpeed(piles, h):
l, r = 1, max(piles)
while l < r:
m = (l + r) // 2
hours = sum(math.ceil(p / m) for p in piles)
if hours <= h:
r = m
else:
l = m + 1
return l
",1,GPT,"Given an array piles where piles[i] is the number of bananas in the ith pile,
and an integer h representing hours,
find the minimum integer eating speed k such that Koko can eat all bananas within h hours.",PYTHON
,"class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
l, r = 1, max(piles)
res = r
while l <= r:
k = (l + r) // 2
totalTime = 0
for p in piles:
totalTime += math.ceil(float(p) / k)
if totalTime <= h:
res = k
r = k - 1
else:
l = k + 1
return res",0,GFG,NA,PYTHON
,"def searchMatrix(matrix, target):
if not matrix or not matrix[0]:
return False
rows, cols = len(matrix), len(matrix[0])
l, r = 0, rows * cols - 1
while l <= r:
m = (l + r) // 2
val = matrix[m // cols][m % cols]
if val == target:
return True
elif val < target:
l = m + 1
else:
r = m - 1
return False
",1,GPT,"Solve the problem ""Search a 2D Matrix"".
The matrix has the following properties:
- Integers in each row are sorted
- First integer of each row is greater than the last integer of the previous row
Given a target, return true if found.
Provide O(log(m*n)) Python solution.
",PYTHON
,"class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
ROWS, COLS = len(matrix), len(matrix[0])
l, r = 0, ROWS * COLS - 1
while l <= r:
m = l + (r - l) // 2
row, col = m // COLS, m % COLS
if target > matrix[row][col]:
l = m + 1
elif target < matrix[row][col]:
r = m - 1
else:
return True
return False",0,GFG,NA,PYTHON
,"def findMedianSortedArrays(nums1, nums2):
A, B = nums1, nums2
if len(A) > len(B):
A, B = B, A
total = len(A) + len(B)
half = total // 2
l, r = 0, len(A)
while True:
i = (l + r) // 2
j = half - i
Aleft = A[i - 1] if i > 0 else float('-inf')
Aright = A[i] if i < len(A) else float('inf')
Bleft = B[j - 1] if j > 0 else float('-inf')
Bright = B[j] if j < len(B) else float('inf')
if Aleft <= Bright and Bleft <= Aright:
if total % 2:
return min(Aright, Bright)
return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
elif Aleft > Bright:
r = i - 1
else:
l = i + 1
",1,GPT,"Solve the problem ""Median of Two Sorted Arrays"".
Given two sorted arrays nums1 and nums2,
return the median of the two sorted arrays.
The overall time complexity must be O(log(min(n, m))).",PYTHON
,"class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
A, B = nums1, nums2
total = len(nums1) + len(nums2)
half = total // 2
if len(B) < len(A):
A, B = B, A
l, r = 0, len(A) - 1
while True:
i = (l + r) // 2
j = half - i - 2
Aleft = A[i] if i >= 0 else float(""-infinity"")
Aright = A[i + 1] if (i + 1) < len(A) else float(""infinity"")
Bleft = B[j] if j >= 0 else float(""-infinity"")
Bright = B[j + 1] if (j + 1) < len(B) else float(""infinity"")
if Aleft <= Bright and Bleft <= Aright:
if total % 2:
return min(Aright, Bright)
return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
elif Aleft > Bright:
r = i - 1
else:
l = i + 1",0,GFG,NA,PYTHON
,"def reverseList(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
",1,GPT,"Solve the problem ""Reverse a Linked List"".
Given the head of a singly linked list,
reverse the list and return the new head.",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev, curr = None, head
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev",0,GFG,NA,PYTHON
,"def reorderList(head):
if not head:
return
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
prev, curr = None, slow.next
slow.next = None
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
first, second = head, prev
while second:
tmp1, tmp2 = first.next, second.next
first.next = second
second.next = tmp1
first, second = tmp1, tmp2
",1,GPT,"Solve the problem ""Reorder Linked List"".
Reorder the list as:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
Do it in-place with O(1) extra space.
",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
second = slow.next
prev = slow.next = None
while second:
tmp = second.next
second.next = prev
prev = second
second = tmp
first, second = head, prev
while second:
tmp1, tmp2 = first.next, second.next
first.next = second
second.next = tmp1
first, second = tmp1, tmp2",0,GFG,NA,PYTHON
,"def findDuplicate(nums):
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
",1,GPT,"Solve the problem ""Find the Duplicate Number"".
Given an array nums containing n+1 integers where each integer is in the range [1, n],
return the duplicate number without modifying the array
and using constant extra space.
Provide Python solution using cycle detection.
",PYTHON
,"class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow, fast = 0, 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow2 = 0
while True:
slow = nums[slow]
slow2 = nums[slow2]
if slow == slow2:
return slow",0,GFG,NA,PYTHON
,"def mergeTwoLists(l1, l2):
dummy = curr = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
",1,GPT,"Solve the problem ""Merge Two Sorted Linked Lists"".
Given two sorted linked lists,
merge them into one sorted list and return its head.",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
dummy = node = ListNode()
while list1 and list2:
if list1.val < list2.val:
node.next = list1
list1 = list1.next
else:
node.next = list2
list2 = list2.next
node = node.next
node.next = list1 or list2
return dummy.next",0,GFG,NA,PYTHON
,"def reverseKGroup(head, k):
dummy = ListNode(0)
dummy.next = head
prev = dummy
while True:
kth = prev
for _ in range(k):
kth = kth.next
if not kth:
return dummy.next
nxt = kth.next
curr = prev.next
for _ in range(k):
tmp = curr.next
curr.next = nxt
nxt = curr
curr = tmp
tmp = prev.next
prev.next = kth
prev = tmp
",1,GPT,"Solve the problem ""Reverse Nodes in K-Group"".
Given a linked list, reverse the nodes of the list k at a time.
If the number of nodes is not a multiple of k, leave them as is.
Provide Python solution.
",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
groupPrev = dummy
while True:
kth = self.getKth(groupPrev, k)
if not kth:
break
groupNext = kth.next
prev, curr = kth.next, groupPrev.next
while curr != groupNext:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
tmp = groupPrev.next
groupPrev.next = kth
groupPrev = tmp
return dummy.next
def getKth(self, curr, k):
while curr and k > 0:
curr = curr.next
k -= 1
return curr",0,GFG,NA,PYTHON
,"def invertTree(root):
if not root:
return None
root.left, root.right = invertTree(root.right), invertTree(root.left)
return root
",1,GPT,"Solve the problem ""Invert Binary Tree"".
Given the root of a binary tree,
invert the tree and return its root.
Provide Python solution.
",PYTHON
,"# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root",0,GFG,NA,PYTHON
,"def isBalanced(root):
def dfs(node):
if not node:
return 0
left = dfs(node.left)
if left == -1:
return -1
right = dfs(node.right)
if right == -1:
return -1
if abs(left - right) > 1:
return -1
return 1 + max(left, right)
return dfs(root) != -1
",1,GPT,"Solve the problem ""Balanced Binary Tree"".
Given a binary tree,
determine if it is height-balanced.
Provide Python solution.
",PYTHON
,"# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root",0,GFG,NA,PYTHON
,"def isSubtree(root, subRoot):
def isSame(a, b):
if not a and not b:
return True
if not a or not b or a.val != b.val:
return False
return isSame(a.left, b.left) and isSame(a.right, b.right)
if not root:
return False
if isSame(root, subRoot):
return True
return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)
",1,GPT,"Solve the problem ""Subtree of Another Tree"".
Given the roots of two binary trees root and subRoot,
return true if there is a subtree of root with the same structure and values as subRoot.
Provide Python solution.
",PYTHON
,"# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def serialize(self, root: Optional[TreeNode]) -> str:
if root == None:
return ""$#""
return (""$"" + str(root.val) + self.serialize(root.left) + self.serialize(root.right))
def z_function(self, s: str) -> list:
z = [0] * len(s)
l, r, n = 0, 0, len(s)
for i in range(1, n):
if i <= r:
z[i] = min(r - i + 1, z[i - l])
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] - 1 > r:
l, r = i, i + z[i] - 1
return z
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
serialized_root = self.serialize(root)
serialized_subRoot = self.serialize(subRoot)
combined = serialized_subRoot + ""|"" + serialized_root
z_values = self.z_function(combined)
sub_len = len(serialized_subRoot)
for i in range(sub_len + 1, len(combined)):
if z_values[i] == sub_len:
return True
return False",0,GFG,NA,PYTHON
,"from collections import deque
def levelOrder(root):
if not root:
return []
res = []
q = deque([root])
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(level)
return res
",1,GPT,"Solve the problem ""Binary Tree Level Order Traversal"".
Given the root of a binary tree,
return the level order traversal of its nodes' values.
Provide Python solution using BFS.
",PYTHON
,"# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
res = []
q = collections.deque()
q.append(root)
while q:
qLen = len(q)
level = []
for i in range(qLen):
node = q.popleft()
if node:
level.append(node.val)
q.append(node.left)
q.append(node.right)
if level:
res.append(level)
return res",0,GFG,NA,PYTHON
,"def exist(board, word):
rows, cols = len(board), len(board[0])
def dfs(r, c, i):
if i == len(word):
return True
if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[i]:
return False
tmp = board[r][c]
board[r][c] = ""#""
found = (dfs(r+1, c, i+1) or dfs(r-1, c, i+1) or
dfs(r, c+1, i+1) or dfs(r, c-1, i+1))
board[r][c] = tmp
return found
for r in range(rows):
for c in range(cols):
if dfs(r, c, 0):
return True
return False
",1,GPT,"Solve the problem ""Word Search"".
Given a 2D board of characters and a word,
return true if the word exists in the grid.
The word can be constructed from adjacent cells
(horizontal or vertical) without reusing a cell.",PYTHON
,"class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
ROWS, COLS = len(board), len(board[0])
def dfs(r, c, i):
if i == len(word):
return True
if (r < 0 or c < 0 or r >= ROWS or c >= COLS or
word[i] != board[r][c] or board[r][c] == '#'):
return False
board[r][c] = '#'
res = (dfs(r + 1, c, i + 1) or
dfs(r - 1, c, i + 1) or
dfs(r, c + 1, i + 1) or
dfs(r, c - 1, i + 1))
board[r][c] = word[i]
return res
for r in range(ROWS):
for c in range(COLS):
if dfs(r, c, 0):
return True
return False",0,GFG,NA,PYTHON
,"def letterCombinations(digits):
if not digits:
return []
phone = {
""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"",
""5"": ""jkl"", ""6"": ""mno"", ""7"": ""pqrs"",
""8"": ""tuv"", ""9"": ""wxyz""
}
res = []
def backtrack(i, cur):
if i == len(digits):
res.append(cur)
return
for ch in phone[digits[i]]:
backtrack(i + 1, cur + ch)
backtrack(0, """")
return res
",1,GPT,"Solve the problem ""Letter Combinations of a Phone Number"".
Given a string of digits from 2 to 9,
return all possible letter combinations that the number could represent.",PYTHON
,"class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
res = [""""]
digitToChar = {
""2"": ""abc"",
""3"": ""def"",
""4"": ""ghi"",
""5"": ""jkl"",
""6"": ""mno"",
""7"": ""qprs"",
""8"": ""tuv"",
""9"": ""wxyz"",
}
for digit in digits:
tmp = []
for curStr in res:
for c in digitToChar[digit]:
tmp.append(curStr + c)
res = tmp
return res",0,GFG,NA,PYTHON
,"from collections import Counter
def leastInterval(tasks, n):
count = Counter(tasks)
max_freq = max(count.values())
max_count = sum(1 for v in count.values() if v == max_freq)
return max(len(tasks), (max_freq - 1) * (n + 1) + max_count)
",1,GPT,"Solve the problem ""Task Scheduler"".
Given a list of tasks and a cooldown n,
return the least number of units of time needed to finish all tasks
with cooldown constraints.
",PYTHON
,"class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
count = [0] * 26
for task in tasks:
count[ord(task) - ord('A')] += 1
maxf = max(count)
maxCount = 0
for i in count:
maxCount += 1 if i == maxf else 0
time = (maxf - 1) * (n + 1) + maxCount
return max(len(tasks), time)",0,GFG,NA,PYTHON
,"def combinationSum(candidates, target):
res = []
def backtrack(i, total, cur):
if total == target:
res.append(cur[:])
return
if i >= len(candidates) or total > target:
return
cur.append(candidates[i])
backtrack(i, total + candidates[i], cur)
cur.pop()
backtrack(i + 1, total, cur)
backtrack(0, 0, [])
return res
",1,GPT,"Solve the problem ""Combination Sum"".
Given an array of distinct integers candidates and a target,
return all unique combinations where candidates sum to target.
Each number may be used unlimited times.",PYTHON
,"class Solution:
def combinationSum(self, nums: List[int], target: int) -> List[List[int]]:
res = []
nums.sort()
def dfs(i, cur, total):
if total == target:
res.append(cur.copy())
return
for j in range(i, len(nums)):
if total + nums[j] > target:
return
cur.append(nums[j])
dfs(j, cur, total + nums[j])
cur.pop()
dfs(0, [], 0)
return res",0,GFG,NA,PYTHON
,"def generateParenthesis(n):
res = []
def backtrack(opened, closed, cur):
if opened == closed == n:
res.append(cur)
return
if opened < n:
backtrack(opened + 1, closed, cur + ""("")
if closed < opened:
backtrack(opened, closed + 1, cur + "")"")
backtrack(0, 0, """")
return res
",1,GPT,"Solve the problem ""Generate Parentheses"".
Given n pairs of parentheses,
generate all combinations of well-formed parentheses.
Provide Python backtracking solution.
",PYTHON
,"class Solution:
def generateParenthesis(self, n):
res = [[] for _ in range(n+1)]
res[0] = [""""]
for k in range(n + 1):
for i in range(k):
for left in res[i]:
for right in res[k-i-1]:
res[k].append(""("" + left + "")"" + right)
return res[-1]",0,GFG,NA,PYTHON
,"import heapq
def lastStoneWeight(stones):
stones = [-s for s in stones]
heapq.heapify(stones)
while len(stones) > 1:
a = -heapq.heappop(stones)
b = -heapq.heappop(stones)
if a != b:
heapq.heappush(stones, -(a - b))
return -stones[0] if stones else 0
",1,GPT,"Solve the problem ""Last Stone Weight"".
Given a list of stones,
repeatedly smash the two heaviest stones.
Return the weight of the remaining stone or 0.
Provide Python solution using heap.
",PYTHON
,"class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
maxStone = max(stones)
bucket = [0] * (maxStone + 1)
for stone in stones:
bucket[stone] += 1
first = second = maxStone
while first > 0:
if bucket[first] % 2 == 0:
first -= 1
continue
j = min(first - 1, second)
while j > 0 and bucket[j] == 0:
j -= 1
if j == 0:
return first
second = j
bucket[first] -= 1
bucket[second] -= 1
bucket[first - second] += 1
first = max(first - second, second)
return first",0,GFG,NA,PYTHON
,"import heapq
def findKthLargest(nums, k):
return heapq.nlargest(k, nums)[-1]
",1,GPT,"Solve the problem ""Kth Largest Element in an Array"".
Given an integer array nums and an integer k,
return the kth largest element.
Do not sort the entire array.",PYTHON
,"class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
k = len(nums) - k
def quickSelect(l, r):
pivot, p = nums[r], l
for i in range(l, r):
if nums[i] <= pivot:
nums[p], nums[i] = nums[i], nums[p]
p += 1
nums[p], nums[r] = nums[r], nums[p]
if p > k:
return quickSelect(l, p - 1)
elif p < k:
return quickSelect(p + 1, r)
else:
return nums[p]
return quickSelect(0, len(nums) - 1)",0,GFG,NA,PYTHON
,"def subsetsWithDup(nums):
nums.sort()
res = []
def backtrack(i, cur):
res.append(cur[:])
for j in range(i, len(nums)):
if j > i and nums[j] == nums[j - 1]:
continue
cur.append(nums[j])
backtrack(j + 1, cur)
cur.pop()
backtrack(0, [])
return res
",1,GPT,"Solve the problem ""Subsets II"".
Given an integer array nums that may contain duplicates,
return all possible subsets without duplicate subsets.",PYTHON
,"class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = [[]]
prev_Idx = idx = 0
for i in range(len(nums)):
idx = prev_idx if i >= 1 and nums[i] == nums[i - 1] else 0
prev_idx = len(res)
for j in range(idx, prev_idx):
tmp = res[j].copy()
tmp.append(nums[i])
res.append(tmp)
return res",0,GFG,NA,PYTHON
,"import heapq
def minMeetingRooms(intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x[0])
heap = []
for start, end in intervals:
if heap and heap[0] <= start:
heapq.heappop(heap)
heapq.heappush(heap, end)
return len(heap)
",1,GPT,"Solve the problem ""Meeting Rooms II"".
Given an array of meeting time intervals where intervals[i] = [start, end],
return the minimum number of conference rooms required.",PYTHON
,"""""""
Definition of Interval:
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
""""""
class Solution:
def minMeetingRooms(self, intervals: List[Interval]) -> int:
time = []
for i in intervals:
time.append((i.start, 1))
time.append((i.end, -1))
time.sort(key=lambda x: (x[0], x[1]))
res = count = 0
for t in time:
count += t[1]
res = max(res, count)
return res",0,GFG,NA,PYTHON
,"def setZeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
row_zero = any(matrix[0][c] == 0 for c in range(cols))
col_zero = any(matrix[r][0] == 0 for r in range(rows))
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][c] == 0:
matrix[r][0] = matrix[0][c] = 0
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
if row_zero:
for c in range(cols):
matrix[0][c] = 0
if col_zero:
for r in range(rows):
matrix[r][0] = 0
",1,GPT,"Solve the problem ""Set Matrix Zeroes"".
Given an m x n matrix,
if an element is 0, set its entire row and column to 0.
Do it in-place with constant extra space.
Provide Python solution.
",PYTHON
,"class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
ROWS, COLS = len(matrix), len(matrix[0])
rowZero = False
for r in range(ROWS):
for c in range(COLS):
if matrix[r][c] == 0:
matrix[0][c] = 0
if r > 0:
matrix[r][0] = 0
else:
rowZero = True
for r in range(1, ROWS):
for c in range(1, COLS):
if matrix[0][c] == 0 or matrix[r][0] == 0:
matrix[r][c] = 0
if matrix[0][0] == 0:
for r in range(ROWS):
matrix[r][0] = 0
if rowZero:
for c in range(COLS):
matrix[0][c] = 0",0,GFG,NA,PYTHON
,"def solveNQueens(n):
res = []
cols, diag1, diag2 = set(), set(), set()
board = [["".""] * n for _ in range(n)]
def backtrack(r):
if r == n:
res.append(["""".join(row) for row in board])
return
for c in range(n):
if c in cols or (r - c) in diag1 or (r + c) in diag2:
continue
cols.add(c)
diag1.add(r - c)
diag2.add(r + c)
board[r][c] = ""Q""
backtrack(r + 1)
cols.remove(c)
diag1.remove(r - c)
diag2.remove(r + c)
board[r][c] = "".""
backtrack(0)
return res
",1,GPT,"Solve the problem ""N-Queens"".
Given an integer n,
return all distinct solutions to the n-queens puzzle.",PYTHON
,"class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
col = 0
posDiag = 0
negDiag = 0
res = []
board = [["".""] * n for i in range(n)]
def backtrack(r):
nonlocal col, posDiag, negDiag
if r == n:
copy = ["""".join(row) for row in board]
res.append(copy)
return
for c in range(n):
if ((col & (1 << c)) or (posDiag & (1 << (r + c)))
or (negDiag & (1 << (r - c + n)))):
continue
col ^= (1 << c)
posDiag ^= (1 << (r + c))
negDiag ^= (1 << (r - c + n))
board[r][c] = ""Q""
backtrack(r + 1)
col ^= (1 << c)
posDiag ^= (1 << (r + c))
negDiag ^= (1 << (r - c + n))
board[r][c] = "".""
backtrack(0)
return res",0,GFG,NA,PYTHON
,"def numIslands(grid):
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
count = 0
def dfs(r, c):
if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != ""1"":
return
grid[r][c] = ""0""
dfs(r+1, c)
dfs(r-1, c)
dfs(r, c+1)
dfs(r, c-1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == ""1"":
dfs(r, c)
count += 1
return count
",1,GPT,"Solve the problem ""Number of Islands"".
Given a 2D grid of '1's (land) and '0's (water),
return the number of islands.",PYTHON
,"class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
ROWS, COLS = len(grid), len(grid[0])
islands = 0
def bfs(r, c):
q = deque()
grid[r][c] = ""0""
q.append((r, c))
while q:
row, col = q.popleft()
for dr, dc in directions:
nr, nc = dr + row, dc + col
if (nr < 0 or nc < 0 or nr >= ROWS or
nc >= COLS or grid[nr][nc] == ""0""
):
continue
q.append((nr, nc))
grid[nr][nc] = ""0""
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == ""1"":
bfs(r, c)
islands += 1
return islands",0,GFG,NA,PYTHON
,"from collections import deque
def orangesRotting(grid):
rows, cols = len(grid), len(grid[0])
q = deque()
fresh = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
q.append((r, c))
elif grid[r][c] == 1:
fresh += 1
time = 0
directions = [(1,0), (-1,0), (0,1), (0,-1)]
while q and fresh:
for _ in range(len(q)):
r, c = q.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
q.append((nr, nc))
time += 1
return time if fresh == 0 else -1
",1,GPT,"Solve the problem ""Rotting Oranges"".
Given a grid where:
0 = empty, 1 = fresh, 2 = rotten,
return the minimum minutes to rot all fresh oranges.
If impossible, return -1.
",PYTHON
,"class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
fresh = 0
time = 0
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == 1:
fresh += 1
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
while fresh > 0:
flag = False
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == 2:
for dr, dc in directions:
row, col = r + dr, c + dc
if (row in range(ROWS) and
col in range(COLS) and
grid[row][col] == 1):
grid[row][col] = 3
fresh -= 1
flag = True
if not flag:
return -1
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == 3:
grid[r][c] = 2
time += 1
return time",0,GFG,NA,PYTHON
,"def solve(board):
if not board:
return
rows, cols = len(board), len(board[0])
def dfs(r, c):
if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != ""O"":
return
board[r][c] = ""T""
dfs(r+1, c)
dfs(r-1, c)
dfs(r, c+1)
dfs(r, c-1)
for r in range(rows):
dfs(r, 0)
dfs(r, cols - 1)
for c in range(cols):
dfs(0, c)
dfs(rows - 1, c)
for r in range(rows):
for c in range(cols):
if board[r][c] == ""O"":
board[r][c] = ""X""
elif board[r][c] == ""T"":
board[r][c] = ""O""
",1,GPT,"Solve the problem ""Surrounded Regions"".
Given a board of 'X' and 'O',
capture all regions surrounded by 'X'.",PYTHON
,"class Solution:
def solve(self, board: List[List[str]]) -> None:
ROWS, COLS = len(board), len(board[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def capture():
q = deque()
for r in range(ROWS):
for c in range(COLS):
if (r == 0 or r == ROWS - 1 or
c == 0 or c == COLS - 1 and
board[r][c] == ""O""
):
q.append((r, c))
while q:
r, c = q.popleft()
if board[r][c] == ""O"":
board[r][c] = ""T""
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < ROWS and 0 <= nc < COLS:
q.append((nr, nc))
capture()
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == ""O"":
board[r][c] = ""X""
elif board[r][c] == ""T"":
board[r][c] = ""O""",0,GFG,NA,PYTHON
,"from collections import deque
def ladderLength(beginWord, endWord, wordList):
wordSet = set(wordList)
if endWord not in wordSet:
return 0
q = deque([(beginWord, 1)])
while q:
word, steps = q.popleft()
if word == endWord:
return steps
for i in range(len(word)):
for c in ""abcdefghijklmnopqrstuvwxyz"":
new = word[:i] + c + word[i+1:]
if new in wordSet:
wordSet.remove(new)
q.append((new, steps + 1))
return 0
",1,GPT,"Solve the problem ""Word Ladder"".
Given beginWord, endWord, and a wordList,
return the length of the shortest transformation sequence.",PYTHON
,"class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList or beginWord == endWord:
return 0
m = len(wordList[0])
wordSet = set(wordList)
qb, qe = deque([beginWord]), deque([endWord])
fromBegin, fromEnd = {beginWord: 1}, {endWord: 1}
while qb and qe:
if len(qb) > len(qe):
qb, qe = qe, qb
fromBegin, fromEnd = fromEnd, fromBegin
for _ in range(len(qb)):
word = qb.popleft()
steps = fromBegin[word]
for i in range(m):
for c in range(97, 123):
if chr(c) == word[i]:
continue
nei = word[:i] + chr(c) + word[i + 1:]
if nei not in wordSet:
continue
if nei in fromEnd:
return steps + fromEnd[nei]
if nei not in fromBegin:
fromBegin[nei] = steps + 1
qb.append(nei)
return 0",0,GFG,NA,PYTHON
,"import heapq
def swimInWater(grid):
n = len(grid)
heap = [(grid[0][0], 0, 0)]
visited = set()
while heap:
time, r, c = heapq.heappop(heap)
if (r, c) in visited:
continue
visited.add((r, c))
if r == n - 1 and c == n - 1:
return time
for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
heapq.heappush(heap, (max(time, grid[nr][nc]), nr, nc))
",1,GPT,"Solve the problem ""Swim in Rising Water"".
Given an n x n grid,
return the minimum time required to swim from top-left to bottom-right.",PYTHON
,"class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
N = len(grid)
visit = set()
minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c)
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
visit.add((0, 0))
while minH:
t, r, c = heapq.heappop(minH)
if r == N - 1 and c == N - 1:
return t
for dr, dc in directions:
neiR, neiC = r + dr, c + dc
if (neiR < 0 or neiC < 0 or
neiR == N or neiC == N or
(neiR, neiC) in visit
):
continue
visit.add((neiR, neiC))
heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])",0,GFG,NA,PYTHON
,"from collections import deque
def wallsAndGates(rooms):
rows, cols = len(rooms), len(rooms[0])
q = deque()
for r in range(rows):
for c in range(cols):
if rooms[r][c] == 0:
q.append((r, c))
directions = [(1,0), (-1,0), (0,1), (0,-1)]
while q:
r, c = q.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == 2147483647:
rooms[nr][nc] = rooms[r][c] + 1
q.append((nr, nc)) ",1,GPT,"Solve the problem ""Walls and Gates"" (Islands and Treasure).
Given a grid with:
-1 = wall, 0 = gate, INF = empty room,
fill each empty room with distance to its nearest gate.",PYTHON
,"class Solution:
def islandsAndTreasure(self, grid: List[List[int]]) -> None:
ROWS, COLS = len(grid), len(grid[0])
visit = set()
q = deque()
def addCell(r, c):
if (min(r, c) < 0 or r == ROWS or c == COLS or
(r, c) in visit or grid[r][c] == -1
):
return
visit.add((r, c))
q.append([r, c])
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == 0:
q.append([r, c])
visit.add((r, c))
dist = 0
while q:
for i in range(len(q)):
r, c = q.popleft()
grid[r][c] = dist
addCell(r + 1, c)
addCell(r - 1, c)
addCell(r, c + 1)
addCell(r, c - 1)
dist += 1",0,GFG,NA,PYTHON
,"def climbStairs(n):
if n <= 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return b
",1,GPT,"Solve the problem ""Climbing Stairs"".
You can climb 1 or 2 steps at a time.
Given n steps, return how many distinct ways you can climb.",PYTHON
,"class Solution:
def climbStairs(self, n: int) -> int:
one, two = 1, 1
for i in range(n - 1):
temp = one
one = one + two
two = temp
return one",0,GFG,NA,PYTHON
,"def rob(nums):
prev, curr = 0, 0
for n in nums:
prev, curr = curr, max(curr, prev + n)
return curr
",1,GPT,"Solve the problem ""House Robber"".
Given an integer array nums representing the amount of money in each house,
return the maximum amount of money you can rob without robbing adjacent houses.
",PYTHON
,"class Solution:
def rob(self, nums: List[int]) -> int:
rob1, rob2 = 0, 0
for num in nums:
temp = max(num + rob1, rob2)
rob1 = rob2
rob2 = temp
return rob2",0,GFG,NA,PYTHON
,"def coinChange(coins, amount):
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for a in range(1, amount + 1):
for c in coins:
if a - c >= 0:
dp[a] = min(dp[a], dp[a - c] + 1)
return dp[amount] if dp[amount] != amount + 1 else -1
",1,GPT,"Solve the problem ""Coin Change"".
Given an array coins and an integer amount,
return the fewest number of coins needed to make up that amount.
If not possible, return -1.",PYTHON
,"class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
if amount == 0:
return 0
q = deque([0])
seen = [False] * (amount + 1)
seen[0] = True
res = 0
while q:
res += 1
for _ in range(len(q)):
cur = q.popleft()
for coin in coins:
nxt = cur + coin
if nxt == amount:
return res
if nxt > amount or seen[nxt]:
continue
seen[nxt] = True
q.append(nxt)
return -1",0,GFG,NA,PYTHON
,"def uniquePaths(m, n):
dp = [1] * n
for _ in range(m - 1):
for j in range(1, n):
dp[j] += dp[j - 1]
return dp[-1]
",1,GPT,"Solve the problem ""Unique Paths"".
Given m and n representing grid dimensions,
return the number of unique paths from top-left to bottom-right.",PYTHON
,"class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [1] * n
for i in range(m - 2, -1, -1):
for j in range(n - 2, -1, -1):
dp[j] += dp[j + 1]
return dp[0]",0,GFG,NA,PYTHON
,"def maxCoins(nums):
nums = [1] + nums + [1]
n = len(nums)
dp = [[0] * n for _ in range(n)]
for length in range(2, n):
for l in range(0, n - length):
r = l + length
for k in range(l + 1, r):
dp[l][r] = max(
dp[l][r],
nums[l] * nums[k] * nums[r] + dp[l][k] + dp[k][r]
)
return dp[0][n - 1]
",1,GPT,"Solve the problem ""Burst Balloons"".
Given an array nums,
return the maximum coins you can collect by bursting balloons wisely.",PYTHON
,"class Solution:
def maxCoins(self, nums):
n = len(nums)
new_nums = [1] + nums + [1]
dp = [[0] * (n + 2) for _ in range(n + 2)]
for l in range(n, 0, -1):
for r in range(l, n + 1):
for i in range(l, r + 1):
coins = new_nums[l - 1] * new_nums[i] * new_nums[r + 1]
coins += dp[l][i - 1] + dp[i + 1][r]
dp[l][r] = max(dp[l][r], coins)
return dp[1][n]",0,GFG,NA,PYTHON
,"def canJump(nums):
max_reach = 0
for i, n in enumerate(nums):
if i > max_reach:
return False
max_reach = max(max_reach, i + n)
return True
",1,GPT,"Solve the problem ""Jump Game"".
Given an array nums where nums[i] represents maximum jump length,
return true if you can reach the last index.",PYTHON
,"class Solution:
def canJump(self, nums: List[int]) -> bool:
goal = len(nums) - 1
for i in range(len(nums) - 2, -1, -1):
if i + nums[i] >= goal:
goal = i
return goal == 0",0,GFG,NA,PYTHON
,"def canCompleteCircuit(gas, cost):
total = curr = start = 0
for i in range(len(gas)):
total += gas[i] - cost[i]
curr += gas[i] - cost[i]
if curr < 0:
start = i + 1
curr = 0
return start if total >= 0 else -1
",1,GPT,"Solve the problem ""Gas Station"".
Given gas and cost arrays,
return the starting gas station index if you can travel around once.
Otherwise return -1.",PYTHON
,"class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost):
return -1
total = 0
res = 0
for i in range(len(gas)):
total += (gas[i] - cost[i])
if total < 0:
total = 0
res = i + 1
return res",0,GFG,NA,PYTHON
,"def isHappy(n):
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(c) ** 2 for c in str(n))
return n == 1
",1,GPT,"Solve the problem ""Happy Number"".
Determine if a number is happy.
Use cycle detection or a set.
Provide Python solution.
",PYTHON
,"class Solution:
def isHappy(self, n: int) -> bool:
slow, fast = n, self.sumOfSquares(n)
power = lam = 1
while slow != fast:
if power == lam:
slow = fast
power *= 2
lam = 0
fast = self.sumOfSquares(fast)
lam += 1
return True if fast == 1 else False
def sumOfSquares(self, n: int) -> int:
output = 0
while n:
digit = n % 10
digit = digit ** 2
output += digit
n = n // 10
return output",0,GFG,NA,PYTHON
,"def isInterleave(s1, s2, s3):
if len(s1) + len(s2) != len(s3):
return False
dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
dp[0][0] = True
for i in range(len(s1) + 1):
for j in range(len(s2) + 1):
if i > 0:
dp[i][j] |= dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]
if j > 0:
dp[i][j] |= dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]
return dp[-1][-1]
",1,GPT,"Solve the problem ""Interleaving String"".
Given strings s1, s2, and s3,
determine if s3 is formed by interleaving s1 and s2.",PYTHON
,"class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
m, n = len(s1), len(s2)
if m + n != len(s3):
return False
if n < m:
s1, s2 = s2, s1
m, n = n, m
dp = [False for _ in range(n + 1)]
dp[n] = True
for i in range(m, -1, -1):
nextDp = True if i == m else False
for j in range(n, -1, -1):
res = False if j < n else nextDp
if i < m and s1[i] == s3[i + j] and dp[j]:
res = True
if j < n and s2[j] == s3[i + j] and nextDp:
res = True
dp[j] = res
nextDp = dp[j]
return dp[0]",0,GFG,NA,PYTHON
,"def findTargetSumWays(nums, target):
total = sum(nums)
if abs(target) > total or (total + target) % 2:
return 0
s = (total + target) // 2
dp = [0] * (s + 1)
dp[0] = 1
for num in nums:
for i in range(s, num - 1, -1):
dp[i] += dp[i - num]
return dp[s]
",1,GPT,"Solve the problem ""Target Sum"".
Given an array nums and a target,
return the number of ways to assign + or - to reach target.",PYTHON
,"class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
dp = defaultdict(int)
dp[0] = 1
for num in nums:
next_dp = defaultdict(int)
for total, count in dp.items():
next_dp[total + num] += count
next_dp[total - num] += count
dp = next_dp
return dp[target]",0,GFG,NA,PYTHON
,"def numDecodings(s):
if not s or s[0] == ""0"":
return 0
dp1, dp2 = 1, 1
for i in range(1, len(s)):
cur = 0
if s[i] != ""0"":
cur += dp2
if 10 <= int(s[i - 1:i + 1]) <= 26:
cur += dp1
dp1, dp2 = dp2, cur
return dp2
",1,GPT,"Solve the problem ""Decode Ways"".
Given a string s containing digits,
return the number of ways to decode it.",PYTHON
,"class Solution:
def numDecodings(self, s: str) -> int:
dp = dp2 = 0
dp1 = 1
for i in range(len(s) - 1, -1, -1):
if s[i] == ""0"":
dp = 0
else:
dp = dp1
if i + 1 < len(s) and (s[i] == ""1"" or
s[i] == ""2"" and s[i + 1] in ""0123456""
):
dp += dp2
dp, dp1, dp2 = 0, dp, dp1
return dp1",0,GFG,NA,PYTHON
,"import json
json_obj = '{ ""Name"":""David"", ""Class"":""I"", ""Age"":6 }'
python_obj = json.loads(json_obj)
print(""\nJSON data:"")
print(python_obj)
print(""\nName: "",python_obj[""Name""])
print(""Class: "",python_obj[""Class""])
print(""Age: "",python_obj[""Age""]) ",0,WE3RESOURCE,NA,PYTHON
,"import requests
from requests.exceptions import SSLError, RequestException
url = ""https://www.google.com"" # valid SSL certificate
try:
# By default, verify=True, so SSL certificates are checked
response = requests.get(url, timeout=10)
print(""Status Code:"", response.status_code)
print(""SSL certificate verified successfully."")
except SSLError as ssl_err:
print(""SSL Certificate verification failed!"")
print(ssl_err)
except RequestException as req_err:
print(""Request failed:"")
print(req_err) ",1,GPT," Write a Python program to verifiy SSL certificates for HTTPS requests using requests module.
Note: Requests verifies SSL certificates for HTTPS requests, just like a web browser. By default, SSL verification is enabled, and Requests will throw a SSLError if it's unable to verify the certificate",PYTHON
,"import json
# a Python object (dict):
python_obj = {
""name"": ""David"",
""class"":""I"",
""age"": 6
}
print(type(python_obj))
# convert into JSON:
j_data = json.dumps(python_obj)
# result is a JSON string:
print(j_data) ",0,WE3RESOURCE,NA,PYTHON
,"import requests
url = ""https://www.example.com""
# Send GET request
response = requests.get(url)
print(""URL:"", response.url)
print(""Status Code:"", response.status_code)
print(""Reason:"", response.reason)
print(""Encoding:"", response.encoding)
print(""\nHeaders:"")
for key, value in response.headers.items():
print(f""{key}: {value}"")
print(""\nHistory (Redirects):"")
print(response.history)
print(""\nCookies:"")
print(response.cookies)
print(""\nElapsed Time:"")
print(response.elapsed)
print(""\nRequest Info:"")
print(""Method:"", response.request.method)
print(""Request URL:"", response.request.url)
print(""Request Headers:"", response.request.headers)
print(""\nContent (first 500 bytes):"")
print(response.content[:500]) ",1,GPT," Write a Python program to display the contains of different attributes like different attributes like status_code, headers, url, history, encoding, reason, cookies, elapsed, request and content of a specified resource.",PYTHON
,"import json
python_dict = {""name"": ""David"", ""age"": 6, ""class"":""I""}
python_list = [""Red"", ""Green"", ""Black""]
python_str = ""Python Json""
python_int = (1234)
python_float = (21.34)
python_T = (True)
python_F = (False)
python_N = (None)
json_dict = json.dumps(python_dict)
json_list = json.dumps(python_list)
json_str = json.dumps(python_str)
json_num1 = json.dumps(python_int)
json_num2 = json.dumps(python_float)
json_t = json.dumps(python_T)
json_f = json.dumps(python_F)
json_n = json.dumps(python_N)
print(""json dict : "", json_dict)
print(""jason list : "", json_list)
print(""json string : "", json_str)
print(""json number1 : "", json_num1)
print(""json number2 : "", json_num2)
print(""json true : "", json_t)
print(""json false : "", json_f)
print(""json null ; "", json_n) ",0,WE3RESOURCE,NA,PYTHON
,"import requests
import datetime
def get_m4_5_plus_count(start_time: str, end_time: str) -> int:
""""""
Returns the number of earthquakes globally with magnitude >= 4.5
between start_time and end_time (ISO format).
""""""
url = ""https://earthquake.usgs.gov/fdsnws/event/1/query""
params = {
""format"": ""geojson"",
""starttime"": start_time,
""endtime"": end_time,
""minmagnitude"": 4.5,
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
# 'count' field in 'metadata' holds the number of matching events
return data.get(""metadata"", {}).get(""count"", 0)
else:
print(f""Error: {response.status_code}"")
return 0
if __name__ == ""__main__"":
# Set time period (last 30 days)
end_time = datetime.datetime.utcnow().date().isoformat()
start_time = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).date().isoformat()
count = get_m4_5_plus_count(start_time, end_time)
print(f""Number of earthquakes with magnitude >= 4.5 between {start_time} and {end_time}: {count}"") ",1,GPT,Write a Python program to get the number of magnitude 4.5+ earthquakes detected worldwide by the USGS.,PYTHON
,"import json
j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
print(""Original String:"")
print(j_str)
print(""\nJSON data:"")
print(json.dumps(j_str, sort_keys=True, indent=4)) ",0,WE3RESOURCE,NA,PYTHON
,"import requests
import random
API_KEY = ""YOUR_TMDB_API_KEY"" # <-- replace with your API key
BASE_URL = ""https://api.themoviedb.org/3""
# Step 1: Get popular movies (several pages available)
popular_url = f""{BASE_URL}/movie/popular""
params = {
""api_key"": API_KEY,
""language"": ""en-US"",
""page"": random.randint(1, 20) # random page for randomness
}
response = requests.get(popular_url, params=params)
response.raise_for_status()
movies = response.json()[""results""]
# Step 2: Randomly select 10 movies
random_movies = random.sample(movies, 10)
print(""Top 10 Random Movies:\n"")
for i, movie in enumerate(random_movies, start=1):
title = movie[""title""]
year = movie[""release_date""][:4] if movie[""release_date""] else ""N/A""
summary = movie[""overview""]
print(f""{i}. Movie Name : {title}"")
print(f"" Year : {year}"")
print(f"" Summary : {summary}\n"") ",1,GPT,"Write a Python program to get movie name, year and a brief summary of the top 10 random movies",PYTHON
,"import json
jobj_dict = '{""name"": ""David"", ""age"": 6, ""class"": ""I""}'
jobj_list = '[""Red"", ""Green"", ""Black""]'
jobj_string = '""Python Json""'
jobj_int = '1234'
jobj_float = '21.34'
python_dict = json.loads(jobj_dict)
python_list = json.loads(jobj_list)
python_str = json.loads(jobj_string)
python_int = json.loads(jobj_int)
python_float = json.loads(jobj_float)
print(""Python dictionary: "", python_dict)
print(""Python list: "", python_list)
print(""Python string: "", python_str)
print(""Python integer: "", python_int)
print(""Python float: "", python_float) ",0,WE3RESOURCE,NA,PYTHON
,"import requests, time
from bs4 import BeautifulSoup
B=""https://www.imdb.com""; H={""User-Agent"":""Mozilla/5.0""}
s=BeautifulSoup(requests.get(B+""/chart/top/"",headers=H).text,""html.parser"")
for m in s.select(""td.titleColumn""):
t=m.a.text; y=m.span.text.strip(""()""); u=B+m.a[""href""]
d=BeautifulSoup(requests.get(u,headers=H).text,""html.parser"").select(""div.credit_summary_item"")
dr="", "".join(a.text for a in d[0].select(""a""))
st="", "".join(a.text for a in d[1].select(""a"") if ""name"" in a[""href""])
print(f""{t} ({y}) | Dir: {dr} | Stars: {st}"")
time.sleep(0.5) ",1,GPT,"Write a Python program to download IMDB's Top 250 data (movie name, Initial release, director name and stars).GIVE ME THE CODE AS SHORT AS POSSIBLE",PYTHON
,"import json
with open('states.json') as f:
state_data= json.load(f)
for state in state_data['states']:
del state['area_codes']
with open('new_states.json', 'w') as f:
json.dump(state_data, f, indent=2) ",0,WE3RESOURCE,NA,PYTHON
,"import requests
from bs4 import BeautifulSoup
url = ""https://mlh.io/seasons/2026/events""
headers = {""User-Agent"":""Mozilla/5.0""}
# Fetch event list
resp = requests.get(url, headers=headers)
soup = BeautifulSoup(resp.text, ""html.parser"")
events = soup.select("".event-card"")[:25] # next 25 events
print(f""{'Date':<20}{'Days':<10}{'Title':<50}{'City':<20}{'Country'}"")
for e in events:
date = e.select_one("".event-date"").text.strip() if e.select_one("".event-date"") else ""N/A""
title = e.select_one("".event-name"").text.strip() if e.select_one("".event-name"") else ""N/A""
location = e.select_one("".event-location"").text.strip().split("","") if e.select_one("".event-location"") else [""N/A""]
city = location[0].strip() if len(location)>0 else ""N/A""
country = location[-1].strip() if len(location)>1 else ""N/A""
# compute approximate event duration if date range present
days = ""1"" if ""-"" not in date else date.split(""-"")[1].strip()
print(f""{date:<20}{days:<10}{title:<50}{city:<20}{country}"") ",1,GPT,"Write a Python program to display the date, days, title, city, country of next 25 Hackevents.",PYTHON
,"import json
def encode_complex(object):
# check using isinstance method
if isinstance(object, complex):
return [object.real, object.imag]
# raised error if object is not complex
raise TypeError(repr(object) + "" is not JSON serialized"")
complex_obj = json.dumps(2 + 3j, default=encode_complex)
print(complex_obj) ",0,WE3RESOURCE,NA,PYTHON
,"import requests
API_KEY = ""YOUR_API_KEY_HERE"" # <-- put your API key here
city = input(""Enter city name: "")
url = ""https://api.openweathermap.org/data/2.5/weather""
params = {
""q"": city,
""appid"": API_KEY,
""units"": ""metric"" # Celsius
}
try:
r = requests.get(url, params=params, timeout=10)
r.raise_for_status()
data = r.json()
temp = data[""main""][""temp""]
wind = data[""wind""][""speed""]
weather = data[""weather""][0][""main""]
desc = data[""weather""][0][""description""]
print(""\nLive Weather Report"")
print(""-------------------"")
print(""City :"", city)
print(""Temperature :"", temp, ""°C"")
print(""Wind Speed :"", wind, ""m/s"")
print(""Weather :"", weather)
print(""Description :"", desc)
except requests.exceptions.RequestException as e:
print(""Error fetching weather data:"", e) ",1,GPT," Write a Python program to find the live weather report (temperature, wind speed, description and weather) of a given city.let the code u give me be efficient and clear ",PYTHON
,"import json
def is_complex_num(objct):
if '__complex__' in objct:
return complex(objct['real'], objct['img'])
return objct
complex_object =json.loads('{""__complex__"": true, ""real"": 4, ""img"": 5}', object_hook = is_complex_num)
simple_object =json.loads('{""real"": 4, ""img"": 3}', object_hook = is_complex_num)
print(""Complex_object: "",complex_object)
print(""Without complex object: "",simple_object)
",0,WE3RESOURCE,NA,PYTHON
,"import snscrape.modules.twitter as sntwitter
username = input(""Enter Twitter username: "")
count = 0
for i, _ in enumerate(sntwitter.TwitterUserScraper(username).get_items()):
if i == 1000: break
count += 1
print(f""Tweets counted (latest 1000 max): {count}"")
",1,GPT,Write a Python program to scrap number of tweets of a given Twitter account. ASK THE USER TO INPUT THIER ACCOUNT ,PYTHON
,"import json
python_obj = '{""a"": 1, ""a"": 2, ""a"": 3, ""a"": 4, ""b"": 1, ""b"": 2}'
print(""Original Python object:"")
print(python_obj)
json_obj = json.loads(python_obj)
print(""\nUnique Key in a JSON object:"")
print(json_obj)
",0,WE3RESOURCE,NA,PYTHON
,"import tweepy
# Replace with your actual bearer token from Twitter Developer Portal
BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
# Initialize the client with bearer token (sufficient for read access)
client = tweepy.Client(bearer_token=BEARER_TOKEN)
# Input for Twitter username (without @)
username = input(""Enter Twitter username: "")
try:
# Get the user by username
user = client.get_user(username=username)
if user.data:
# Access public_metrics which includes total tweet count
public_metrics = user.data.public_metrics
tweet_count = public_metrics['tweet_count']
print(f""@{username} has posted {tweet_count:,} tweets (including retweets and replies)."")
else:
print(""User not found."")
except tweepy.TweepyException as e:
print(f""Error: {e}"")
",1,PERPLEXITY,Write a Python program to count number of tweets by a given Twitter account. add a input feature where the user would give their account as an input .,PYTHON
,"from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://www.wikipedia.org/')
bs = BeautifulSoup(html, ""html.parser"")
nameList = bs.findAll('a', {'class' : 'link-box'})
for name in nameList:
print(name.get_text())
",0,WE3RESOURCE,NA,PYTHON
,"import tweepy
# Replace with your actual bearer token from X Developer Portal
BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
# Initialize the client with bearer token (sufficient for read access)
client = tweepy.Client(bearer_token=BEARER_TOKEN)
# Input for Twitter username (without @)
username = input(""Enter Twitter username: "")
try:
# Get the user by username
user = client.get_user(username=username, user_fields=['public_metrics'])
if user.data:
# Access public_metrics.like_count for number of liked posts
public_metrics = user.data.public_metrics
likes_count = public_metrics['like_count']
print(f""@{username} has liked {likes_count:,} posts."")
else:
print(""User not found."")
except tweepy.TweepyException as e:
print(f""Error: {e}"") ",1,PERPLEXITY,Write a Python program to get the number of post on Twitter liked by a given account,PYTHON
,"#https://bit.ly/2lVhlLX
# via: https://analytics.usa.gov/
import requests
url = 'https://analytics.usa.gov/data/live/realtime.json'
j = requests.get(url).json()
print(""Number of people visiting a U.S. government website-"")
print(""Active Users Right Now:"")
print(j['data'][0]['active_visitors'])
",0,WE3RESOURCE,NA,PYTHON
,"import tweepy
# Replace with your actual bearer token from X Developer Portal
BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
# Initialize the client with bearer token (sufficient for read access)
client = tweepy.Client(bearer_token=BEARER_TOKEN)
# Input for Twitter username (without @)
username = input(""Enter Twitter username: "")
try:
# Get the user by username with public_metrics
user = client.get_user(username=username, user_fields=['public_metrics'])
if user.data:
# Access public_metrics.following count
public_metrics = user.data.public_metrics
following_count = public_metrics['following']
print(f""@{username} is following {following_count:,} accounts."")
else:
print(""User not found."")
except tweepy.TweepyException as e:
print(f""Error: {e}"") ",1,PERPLEXITY,Write a Python program to get the number of following on a Twitter account.,PYTHON
,"#https://bit.ly/2lVhlLX
import requests
from lxml import html
url = 'https://www.us-cert.gov/ncas/alerts'
doc = html.fromstring(requests.get(url).text)
print(""The number of security alerts issued by US-CERT in the current year:"")
print(len(doc.cssselect('.item-list li')))
",0,WE3RESOURCE,NA,PYTHON
,"import tweepy
client = tweepy.Client(bearer_token='YOUR_BEARER_TOKEN_HERE')
username = input(""Enter Twitter username: "")
try:
user = client.get_user(username=username, user_fields=['public_metrics'])
print(f""@{username} has {user.data.public_metrics['followers_count']:,} followers"")
except:
print(""Error fetching data"") ",1,PERPLEXITY,Write a Python program to get the number of followers of a given twitter account. GIVE THE CODE IN FEWER LINES FOR EFFECTIVENESS,PYTHON
,"#https://bit.ly/2lVhlLX
import requests
from lxml import html
url = 'http://www.state.gov/r/pa/ode/socialmedia/'
doc = html.fromstring(requests.get(url).text)
pinlinks = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]
print(""The number of Pinterest accounts maintained by U.S. State Department embassies and missions:"")
print(len(pinlinks))
",0,WE3RESOURCE,NA,PYTHON
,"import requests
from lxml import html
url = 'https://www.state.gov/r/pa/ode/socialmedia/'
doc = html.fromstring(requests.get(url).text)
pinterest_links = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]
print(f""Number of Pinterest accounts: {len(pinterest_links)}"") ",1,PERPLEXITY," Write a Python program to get the number of Pinterest accounts maintained by U.S. State Department embassies and missions.
Source: https://www.state.gov/r/pa/ode/socialmedia/",PYTHON
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
follow_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--followers'})
followers = follow_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""Number of followers: {} "".format(followers.get('data-count')))
except:
print('Account name not found...')
",0,WERESOURCE,NA,PYTHON
,"import requests
from bs4 import BeautifulSoup
from datetime import datetime
url = 'https://www.us-cert.gov/ncas/alerts'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Current year
current_year = datetime.now().year
alerts = soup.find_all('article', {'data-year': str(current_year)})
print(f""US-CERT security alerts in {current_year}: {len(alerts)}"") ",1,PERPLEXITY,"Write a Python program get the number of security alerts issued by US-CERT in the current year.
Source: https://www.us-cert.gov/ncas/alerts",PYTHON
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
favorite_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--favorites'})
favorite = favorite_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""Number of post {} liked are {}: "".format(handle,favorite.get('data-count')))
except:
print('Account name not found...')
",0,WERESOURCE,NA,PYTHON
,"import requests
import json
url = 'https://analytics.usa.gov/data/live/realtime.json'
data = requests.get(url).json()
active_users = data['totals']['activeUsers']
print(f""Currently {active_users:,} people visiting U.S. government websites"") ",1,PERPLEXITY,"Write a Python program to get the number of people visiting a U.S. government website right now.
Source: https://analytics.usa.gov/data/live/realtime.json",PYTHON
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
following_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--following'})
following = following_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""{} is following {} people."".format(handle,following.get('data-count')))
except:
print('Account name not found...')
",0,WERESOURCE,NA,PYTHON
,"import requests
from bs4 import BeautifulSoup
url = 'https://www.wikipedia.org/'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
langs = soup.find('ul', class_='languages').find_all('li')
for lang in langs:
name = lang.text.strip()
count = lang.a['title'].split(' ')[0].replace(',', '')
print(f""{name}: {count}"") ",1,PERPLEXITY,Write a Python program to list all language names and number of related articles in the order they appear in wikipedia.org.,PYTHON
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
tweet_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--tweets is-active'})
tweets= tweet_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""{} tweets {} number of tweets."".format(handle,tweets.get('data-count')))
except:
print('Account name not found...')
",0,WERESOURCE,NA,PYTHON
,"import json
import io
def convert_json_to_object(data_source):
""""""
Converts JSON data from various forms (string, file, or stream)
into a Python object.
""""""
try:
# Case 1: If data_source is already a file-like object/stream
if hasattr(data_source, 'read'):
return json.load(data_source)
# Case 2: If data_source is a string
if isinstance(data_source, str):
# Check if it's a file path by looking for a .json extension
if data_source.strip().endswith('.json'):
with open(data_source, 'r', encoding='utf-8') as f:
return json.load(f)
# Otherwise, treat it as a raw JSON string
return json.loads(data_source)
# Case 3: If data_source is bytes
if isinstance(data_source, bytes):
return json.loads(data_source.decode('utf-8'))
raise ValueError(""Unsupported data format."")
except json.JSONDecodeError as e:
return f""Invalid JSON: {e}""
except FileNotFoundError:
return ""Error: The specified file was not found.""
# --- Examples of Usage ---
# 1. From a JSON String
json_string = '{""name"": ""Alice"", ""role"": ""Engineer"", ""active"": true}'
obj_from_str = convert_json_to_object(json_string)
# 2. From a File-like object (Stream)
stream = io.StringIO('[1, 2, 3, {""key"": ""value""}]')
obj_from_stream = convert_json_to_object(stream)
print(f""String conversion: {obj_from_str['name']}"")
print(f""Stream conversion: {obj_from_stream[3]['key']}"")",1,GEMINI,Write a Python program to convert JSON data to Python object.Make the code effiecient to accept the json in various countforms,PYTHON
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
ctr = int(input('Input number of tweets to scrape: '))
res=requests.get('https://twitter.com/'+ handle)
bs=BeautifulSoup(res.content,'lxml')
all_tweets = bs.find_all('div',{'class':'tweet'})
if all_tweets:
for tweet in all_tweets[:ctr]:
context = tweet.find('div',{'class':'context'}).text.replace(""\n"","" "").strip()
content = tweet.find('div',{'class':'content'})
header = content.find('div',{'class':'stream-item-header'})
user = header.find('a',{'class':'account-group js-account-group js-action-profile js-user-profile-link js-nav'}).text.replace(""\n"","" "").strip()
time = header.find('a',{'class':'tweet-timestamp js-permalink js-nav js-tooltip'}).find('span').text.replace(""\n"","" "").strip()
message = content.find('div',{'class':'js-tweet-text-container'}).text.replace(""\n"","" "").strip()
footer = content.find('div',{'class':'stream-item-footer'})
stat = footer.find('div',{'class':'ProfileTweet-actionCountList u-hiddenVisually'}).text.replace(""\n"","" "").strip()
if context:
print(context)
print(user,time)
print(message)
print(stat)
print()
else:
print(""List is empty/account name not found."")
",0,WERESOURCE,NA,PYTHON
,"import json
def convert_to_json(data, indent=4):
""""""
Converts a Python object to a JSON string.
Includes a fallback for custom objects that aren't natively serializable.
""""""
try:
# indent=4 makes the output 'pretty' and readable
# sort_keys=True organizes the dictionary keys alphabetically
return json.dumps(data, indent=indent, sort_keys=True, default=str)
except Exception as e:
return f""Error converting to JSON: {e}""
# --- Examples of Usage ---
# 1. Converting a standard Dictionary
user_profile = {
""username"": ""coder_123"",
""id"": 882,
""tags"": [""python"", ""api"", ""json""],
""is_premium"": False,
""location"": None
}
json_output = convert_to_json(user_profile)
print(""--- Standard Dictionary to JSON ---"")
print(json_output)
# 2. Converting to a JSON File
with open(""data.json"", ""w"", encoding=""utf-8"") as f:
json.dump(user_profile, f, indent=4)
print(""\n[System] Data successfully written to data.json"")",1,GEMINI,Write a Python program to convert Python object to JSON data.,PYTHON
,"import requests
from pprint import pprint
def weather_data(query):
res=requests.get('http://api.openweathermap.org/data/2.5/weather?'+query+'&APPID=****************************8&units=metric');
return res.json();
def print_weather(result,city):
print(""{}'s temperature: {}°C "".format(city,result['main']['temp']))
print(""Wind speed: {} m/s"".format(result['wind']['speed']))
print(""Description: {}"".format(result['weather'][0]['description']))
print(""Weather: {}"".format(result['weather'][0]['main']))
def main():
city=input('Enter the city:')
print()
try:
query='q='+city;
w_data=weather_data(query);
print_weather(w_data, city)
print()
except:
print('City name not found...')
if __name__=='__main__':
main()
",0,WERESOURCE,NA,PYTHON
,"import json
def python_to_json_display(data):
# Convert Python object to a JSON formatted string
# indent=4 adds whitespace for readability
# sort_keys=True keeps the output consistent
json_string = json.dumps(data, indent=4, sort_keys=True)
print(""--- Generated JSON String ---"")
print(json_string)
# To ""print all values"" specifically from the resulting JSON
# we first load it back to iterate through it
print(""\n--- Individual Values Extracted ---"")
parsed_data = json.loads(json_string)
if isinstance(parsed_data, dict):
for key, value in parsed_data.items():
print(f""Key: {key:12} | Value: {value} ({type(value).__name__})"")
# Example Python Object (Dictionary)
employee_data = {
""name"": ""Marcus Aurelius"",
""department"": ""Philosophy"",
""years_active"": 19,
""is_remote"": True,
""skills"": [""Leadership"", ""Writing"", ""Logic""],
""office_id"": None
}
if __name__ == ""__main__"":
python_to_json_display(employee_data)",1,GEMINI,Write a Python program to convert Python objects into JSON strings. Print all the values.,PYTHON
,"import requests
from bs4 import BeautifulSoup
res = requests.get('https://hackevents.co/hackathons')
bs = BeautifulSoup(res.text, 'lxml')
hacks_data = bs.find_all('div',{'class':'hackathon '})
for i,f in enumerate(hacks_data,1):
hacks_month = f.find('div',{'class':'date'}).find('div',{'class':'date-month'}).text.strip()
hacks_date = f.find('div',{'class':'date'}).find('div',{'class':'date-day-number'}).text.strip()
hacks_days = f.find('div',{'class':'date'}).find('div',{'class':'date-week-days'}).text.strip()
hacks_final_date = ""{} {}, {} "".format(hacks_date, hacks_month, hacks_days )
hacks_name = f.find('div',{'class':'info'}).find('h2').text.strip()
hacks_city = f.find('div',{'class':'info'}).find('p').find('span',{'class':'city'}).text.strip()
hacks_country = f.find('div',{'class':'info'}).find('p').find('span',{'class':'country'}).text.strip()
print(""{:<5}{:<15}: {:<90}: {}, {}\n "".format(str(i)+')',hacks_final_date, hacks_name.title(), hacks_city, hacks_country))
",0,WERESOURCE,NA,PYTHON
,"import json
def convert_dict_to_sorted_json(data_dict):
""""""
Converts a dictionary to a JSON string sorted by keys
with an indent of 4 spaces.
""""""
try:
# sort_keys=True: Alphabetizes the keys
# indent=4: Adds 4 spaces for nested members
json_output = json.dumps(data_dict, sort_keys=True, indent=4)
print(""Successfully converted to Sorted JSON:"")
print(json_output)
return json_output
except (TypeError, ValueError) as e:
print(f""Error converting object: {e}"")
return None
# Example dictionary with unsorted keys
blog_post = {
""title"": ""Python JSON Guide"",
""author"": ""Jane Doe"",
""views"": 1500,
""tags"": [""python"", ""json"", ""tutorial""],
""published"": True,
""category"": ""Programming""
}
# Execute conversion
convert_dict_to_sorted_json(blog_post)",1,GEMINI,Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4.,PYTHON
,"#https://bit.ly/2NyxdAG
from bs4 import BeautifulSoup
import requests
import re
# Download IMDB's Top 250 data
url = 'http://www.imdb.com/chart/top'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
movies = soup.select('td.titleColumn')
links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]
crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')]
ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')]
votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')]
imdb = []
# Store each item into dictionary (data), then put those into a list (imdb)
for index in range(0, len(movies)):
# Seperate movie into: 'place', 'title', 'year'
movie_string = movies[index].get_text()
movie = (' '.join(movie_string.split()).replace('.', ''))
movie_title = movie[len(str(index))+1:-7]
year = re.search('\((.*?)\)', movie_string).group(1)
place = movie[:len(str(index))-(len(movie))]
data = {""movie_title"": movie_title,
""year"": year,
""place"": place,
""star_cast"": crew[index],
""rating"": ratings[index],
""vote"": votes[index],
""link"": links[index]}
imdb.append(data)
for item in imdb:
print(item['place'], '-', item['movie_title'], '('+item['year']+') -', 'Starring:', item['star_cast'])
",0,WERESOURCE,NA,PYTHON
,"import json
# JSON encoded data (often received from an API or web request)
json_data = '''
{
""company"": ""TechFlow"",
""location"": ""San Francisco"",
""employees"": 150,
""is_hiring"": true,
""tech_stack"": [""Python"", ""React"", ""PostgreSQL""],
""revenue"": null
}
'''
def decode_json(json_string):
try:
# Convert JSON string to Python object (Dictionary)
python_obj = json.loads(json_string)
print(""Successfully converted JSON to Python Object:"")
print(f""Type: {type(python_obj)}"")
print(""-"" * 30)
# Accessing the data using Python keys
print(f""Company Name: {python_obj['company']}"")
print(f""Main Language: {python_obj['tech_stack'][0]}"")
print(f""Hiring Status: {python_obj['is_hiring']}"")
return python_obj
except json.JSONDecodeError as e:
print(f""Failed to decode JSON: {e}"")
# Execute the conversion
decoded_data = decode_json(json_data)",1,GEMINI,Write a Python program to convert JSON encoded data into Python objects.,PYTHON
,"from bs4 import BeautifulSoup
import requests
import random
def get_imd_movies(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
movies = soup.find_all(""td"", class_=""titleColumn"")
random.shuffle(movies)
return movies
def get_imd_summary(url):
movie_page = requests.get(url)
soup = BeautifulSoup(movie_page.text, 'html.parser')
return soup.find(""div"", class_=""summary_text"").contents[0].strip()
def get_imd_movie_info(movie):
movie_title = movie.a.contents[0]
movie_year = movie.span.contents[0]
movie_url = 'http://www.imdb.com' + movie.a['href']
return movie_title, movie_year, movie_url
def imd_movie_picker():
ctr=0
print(""--------------------------------------------"")
for movie in get_imd_movies('http://www.imdb.com/chart/top'):
movie_title, movie_year, movie_url = get_imd_movie_info(movie)
movie_summary = get_imd_summary(movie_url)
print(movie_title, movie_year)
print(movie_summary)
print(""--------------------------------------------"")
ctr=ctr+1
if (ctr==10):
break;
if __name__ == '__main__':
imd_movie_picker()
",0,WERESOURCE,NA,PYTHON
,"import json
from datetime import datetime
def replicate_json_file(source_filename, destination_filename):
try:
# 1. Open and read the existing JSON file
with open(source_filename, 'r', encoding='utf-8') as source_file:
data = json.load(source_file)
# 2. (Optional) Modify the data
# For example, let's add metadata about when this copy was created
if isinstance(data, dict):
data['processed_at'] = datetime.now().strftime(""%Y-%m-%d %H:%M:%S"")
data['status'] = ""replicated""
# 3. Write the data to a new JSON file
with open(destination_filename, 'w', encoding='utf-8') as dest_file:
# indent=4 makes the new file human-readable
json.dump(data, dest_file, indent=4, sort_keys=True)
print(f""Successfully created '{destination_filename}' from '{source_filename}'."")
except FileNotFoundError:
print(""Error: The source file does not exist."")
except json.JSONDecodeError:
print(""Error: Failed to decode JSON. Check if the source file is valid."")
except Exception as e:
print(f""An unexpected error occurred: {e}"")
# --- Usage ---
# Ensure you have a file named 'source.json' in your directory before running
replicate_json_file('source.json', 'new_backup.json')",1,GEMINI,Write a Python program to create a new JSON file from an existing JSON file.,PYTHON
,"#https://bit.ly/2lVhlLX
# landing page:
# http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php
import csv
import requests
csvurl = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv'
rows = list(csv.DictReader(requests.get(csvurl).text.splitlines()))
print(""The number of magnitude 4.5+ earthquakes detected worldwide by the USGS:"", len(rows))
",0,WERESOURCE,NA,PYTHON
,"def check_if_complex(data):
""""""
Checks if the provided data instance is of the complex type.
""""""
if isinstance(data, complex):
print(f""✓ {data} is a complex number."")
print(f"" - Real part: {data.real}"")
print(f"" - Imaginary part: {data.imag}"")
else:
print(f""✗ {data} (type: {type(data).__name__}) is NOT a complex number."")
# --- Testing various instances ---
# A standard complex number
val1 = 5 + 3j
# A complex number created via constructor
val2 = complex(10, -2)
# A standard integer
val3 = 100
# A float
val4 = 7.5
print(""Starting Instance Check:\n"" + ""-""*25)
check_if_complex(val1)
check_if_complex(val2)
check_if_complex(val3)
check_if_complex(val4)",1,GEMINI,Write a Python program to check whether an instance is complex or not.,PYTHON
,"import requests
response = requests.get('https://python.org')
print(""Status Code: "",response.status_code)
print(""Headers: "",response.headers)
print(""Url: "",response.url)
print(""History: "",response.history)
print(""Encoding: "",response.encoding)
print(""Reason: "",response.reason)
print(""Cookies: "",response.cookies)
print(""Elapsed: "",response.elapsed)
print(""Request: "",response.request)
print(""Content: "",response._content)
",0,WERESOURCE,NA,PYTHON
,"import json
def has_complex_structure(data):
""""""
Recursively checks if a Python object contains nested
collections (dict or list).
""""""
# If the root is a list, check its elements
if isinstance(data, list):
for item in data:
if isinstance(item, (dict, list)):
return True
return False
# If the root is a dict, check if any value is a dict or list
if isinstance(data, dict):
for value in data.values():
if isinstance(value, (dict, list)):
return True
return False
def check_json_complexity(json_str):
try:
parsed = json.loads(json_str)
if has_complex_structure(parsed):
print(""Complexity Found: This JSON contains nested objects/arrays."")
else:
print(""Simple JSON: This is a flat key-value structure."")
except json.JSONDecodeError:
print(""Invalid JSON string."")
# --- Test Cases ---
simple_json = '{""name"": ""Alice"", ""age"": 30}'
complex_json = '{""user"": {""id"": 1, ""name"": ""Alice""}, ""tags"": [""admin"", ""dev""]}'
print(""Checking simple_json:"")
check_json_complexity(simple_json)
print(""\nChecking complex_json:"")
check_json_complexity(complex_json)",1,GEMINI,Write a Python program to check whether a JSON string contains complex object or not,PYTHON
,"import requests
print(requests.get('https://w3resource.com'))
print(requests.get('https://wayback.com'))
",0,WERESOURCE,NA,PYTHON
,"def get_unique_values(data_obj):
# We use set() because sets automatically remove duplicates
unique_values = set(data_obj.values())
return list(unique_values)
# Example: Several keys share the same value
employee_roles = {
""Alice"": ""Engineer"",
""Bob"": ""Manager"",
""Charlie"": ""Engineer"",
""David"": ""Intern"",
""Eve"": ""Manager""
}
print(f""Unique Roles: {get_unique_values(employee_roles)}"")",1,GEMINI,Write a Python program to access only unique key value of a Python object.,PYTHON
,"public class OddEvenArray
{
public static void main(String args[])
{
int s, i;
int[] a = { 33, 2, 4, 71, 88, 92, 9, 1 };
for (i = 0; i < a.length; i++)
{
for (int j = i + 1; j < a.length; j++)
{
if (a[i] > a[j])
{
s = a[i];
a[i] = a[j];
a[j] = s;
}
}
}
System.out.print(""Input numbers :"");
for (i = 0; i < a.length; i++)
{
System.out.print("" "" + a[i]);
}
System.out.print(""\nOdd numbers :"");
for (i = 0; i <= a.length - 1; i++)
{
if (a[i] % 2 != 0)
{
System.out.print("" "" + a[i]);
}
}
System.out.print(""\nEven numbers :"");
for (i = 0; i < a.length; i++)
{
if (a[i] % 2 == 0)
{
System.out.print("" "" + a[i]);
}
}
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String key = String.valueOf(ca);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(map.values());
}",1,GEMINI,"Given an array of strings, group anagrams together.",JAVA
,"class MatrixAddition
{
public static void main(String args[])
{
int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} };
int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} };
int[][] c = new int[3][3];
if(a.length == b.length && a[0].length == b[0].length)
{
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
else
{
System.out.println(""'A' and 'B' Matrix are not SAME"");
return;
}
System.out.println(""The Matrix 'A' Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + "" "");
}
System.out.println();
}
System.out.println(""The Matrix 'B' Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(b[i][j]+ "" "");
}
System.out.println();
}
System.out.println(""The Addition Matrix of 'A' and 'B' Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(c[i][j] + "" "");
}
System.out.println();
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"class LRUCache extends LinkedHashMap<Integer, Integer> {
private final int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75f, true);
this.capacity = capacity;
}
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
}",1,GEMINI,Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.,JAVA
,"class NullMatrix
{
public static void main(String args[])
{
int[][] a = new int[][] { { 0, 0, 0},{ 0, 0, 1},{ 0, 0, 0} };
boolean setValue = true;
abc: for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
if(a[i][j] != 0)
{
setValue = false;
break abc;
}
}
}
System.out.println(""The Given Matrix Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + "" "");
}
System.out.println();
}
if(setValue == true)
{
System.out.println(""The Given Matrix is a Null Matrix"");
}
else
{
System.out.println(""The Given Matrix is not a Null Matrix"");
}
}
} ",0,IPSGWALIOR.ORG,,JAVA
,"public int lengthOfLongestSubstring(String s) {
int max = 0;
Map<Character, Integer> map = new HashMap<>();
for (int j = 0, i = 0; j < s.length(); j++) {
if (map.containsKey(s.charAt(j))) i = Math.max(map.get(s.charAt(j)), i);
max = Math.max(max, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return max;
}",1,GEMINI,Find the length of the longest substring without repeating characters.,JAVA
,"class DiagonalMatrix
{
public static void main(String args[])
{
int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} };
boolean setValue = true;
abc: for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
if(i == j)
{
if(a[i][j] == 0)
{
setValue = false;
break abc;
}
}
else if(a[i][j] != 0)
{
setValue = false;
break abc;
}
}
}
System.out.println(""The Given Matrix Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + "" "");
}
System.out.println();
}
if(setValue == true)
{
System.out.println(""The Given Matrix is a Diagonal Matrix"");
}
else
{
System.out.println(""The Given Matrix is not a Diagonal Matrix"");
}
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"class MinStack {
private Stack<Integer> st = new Stack<>(), minSt = new Stack<>();
public void push(int x) {
st.push(x);
if (minSt.isEmpty() || x <= minSt.peek()) minSt.push(x);
}
public void pop() {
if (st.pop().equals(minSt.peek())) minSt.pop();
}
public int getMin() { return minSt.peek(); }
}",1,GEMINI,"Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.",JAVA
,"import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int i, num, searchval, array[];
Scanner in = new Scanner(System.in);
System.out.println(""Enter number of elements"");
num = in.nextInt();
array = new int[num];
System.out.println(""Enter "" + num + "" integers"");
for (i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println(""Enter the search value:"");
searchval = in.nextInt();
in.close();
for (i = 0; i < num; i++)
{
if (array[i] == searchval)
{
System.out.println(searchval + "" is present at location "" + (i + 1));
break;
}
}
if (i == num)
System.out.println(searchval + "" is not exist in array."");
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int val : nums) {
pq.offer(val);
if (pq.size() > k) pq.poll();
}
return pq.peek();
}",1,GEMINI,Find the kth largest element in an unsorted array.,JAVA
,"import java.util.Scanner;
public class BinarySearch
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
Scanner input = new Scanner(System.in);
System.out.println(""Enter number of elements:"");
num = input.nextInt();
array = new int[num];
System.out.println(""Enter "" + num + "" integers"");
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
System.out.println(""Enter the search value:"");
item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last) / 2;
while (first <= last)
{
if (array[middle] < item)
first = middle + 1;
else if (array[middle] == item)
{
System.out.println(item + "" found at location "" + (middle + 1) + ""."");
break;
}
else
{
last = middle - 1;
}
middle = (first + last) / 2;
}
if (first > last)
System.out.println(item + "" is not found.\n"");
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
for (ListNode l : lists) if (l != null) pq.add(l);
ListNode dummy = new ListNode(0), tail = dummy;
while (!pq.isEmpty()) {
tail.next = pq.poll();
tail = tail.next;
if (tail.next != null) pq.add(tail.next);
}
return dummy.next;
}",1,GEMINI,write a program to Merge k sorted linked lists into one sorted linked list.,JAVA
,"public class FindHCFAndLCM
{
public static void main(String args[])
{
int a, b, x, y, t, hcf, lcm;
x = 6;
y = 10;
a = x;
b = y;
while (b != 0)
{
t = b;
b = a % b;
a = t;
}
hcf = a;
lcm = (x * y) / hcf;
System.out.print(""HCF and LCM of : "" + x + "" and "" + y + "" is :\n"");
System.out.print(""HCF = "" + hcf);
System.out.print(""\nLCM = "" + lcm);
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"public int trap(int[] height) {
int l = 0, r = height.length - 1, lMax = 0, rMax = 0, ans = 0;
while (l < r) {
if (height[l] < height[r]) {
if (height[l] >= lMax) lMax = height[l]; else ans += lMax - height[l];
l++;
} else {
if (height[r] >= rMax) rMax = height[r]; else ans += rMax - height[r];
r--;
}
}
return ans;
}",1,GEMINI,"write a java progrom for Given n non-negative integers representing an elevation map, compute how much water it can trap.",JAVA
,"public class Cube {
public static void main(String arg[]) {
int side=5;
float volume=side * side * side;
System.out.println(""Volume of Cube :""+ volume);
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
return left == null ? right : right == null ? left : root;
}",1,GEMINI,Find the lowest common ancestor of two given nodes in a tree.,JAVA
,"public class ReverseNum
{
public static void main(String[] args)
{
int rev = 0;
int num = 1234;
int no=num;
while (num > 0)
{
int rem = num % 10;
rev = rem + (rev * 10);
num = num / 10;
}
System.out.println(""Number = ""+no);
System.out.println(""Reverse = ""+rev);
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"public int ladderLength(String begin, String end, List<String> wordList) {
Set<String> set = new HashSet<>(wordList);
Queue<String> q = new LinkedList<>(); q.add(begin);
int step = 1;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
char[] cur = q.poll().toCharArray();
for (int j = 0; j < cur.length; j++) {
char tmp = cur[j];
for (char c = 'a'; c <= 'z'; c++) {
cur[j] = c; String next = new String(cur);
if (set.contains(next)) {
if (next.equals(end)) return step + 1;
q.add(next); set.remove(next);
}
}
cur[j] = tmp;
}
}
step++;
}
return 0;
}",1,GEMINI,give me an java program to Find the length of shortest transformation sequence from beginWord to endWord.,JAVA
,"import java.util.HashMap;
import java.util.Scanner;
public class IntegertoRoman
{
private static int[] bases = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
private static HashMap<Integer, String> map = new HashMap<Integer, String>();
private static void setup()
{
map.put(1, ""I"");
map.put(4, ""IV"");
map.put(5, ""V"");
map.put(9, ""IX"");
map.put(10, ""X"");
map.put(40, ""XL"");
map.put(50, ""L"");
map.put(90, ""XC"");
map.put(100, ""C"");
map.put(400, ""CD"");
map.put(500, ""D"");
map.put(900, ""CM"");
map.put(1000, ""M"");
}
public String intToRoman(int num)
{
setup();
String result = new String();
for (int i : bases)
{
while (num >= i)
{
result += map.get(i);
num -= i;
}
}
return result;
}
public static void main(String arg[])
{
System.out.println(""Enter the number : "");
Scanner sc = new Scanner(System.in);
int no = sc.nextInt();
IntegertoRoman in = new IntegertoRoman();
int value=no;
String sd = in.intToRoman(value);
System.out.println(value+"" ---> "" + sd);
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}",1,GEMINI,write a program to Implement a thread-safe Singleton that prevents unnecessary synchronization.,JAVA
,"public class WordCount
{
public static void main(String args[])
{
String s = ""welcome to candid java tutorial"";
int count = 1;
for (int i = 0; i < s.length() - 1; i++)
{
if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' '))
{
count++;
}
}
System.out.println(""Number of words in a string = "" + count);
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"class PC {
LinkedList<Integer> list = new LinkedList<>();
public void produce() throws InterruptedException {
synchronized(this) {
while (list.size() == 1) wait();
list.add(1); notify();
}
}
public void consume() throws InterruptedException {
synchronized(this) {
while (list.isEmpty()) wait();
list.removeFirst(); notify();
}
}
}",1,GEMINI,give me a java program to Implement the Producer-Consumer pattern using wait() and notify(),JAVA
,"public class CountWords
{
public static void main(String[] args)
{
String input=""Welcome to Java Session Session Session"";
String[] words=input.split("" "");
int wrc=1;
for(int i=0;i<words.length;i++)
{
for(int j=i+1;j<words.length;j++)
{
if(words[i].equals(words[j]))
{
wrc=wrc+1;
words[j]=""0"";
}
}
if(words[i]!=""0"")
System.out.println(words[i]+""--""+wrc);
wrc=1;
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"public void deadlock() {
String r1 = ""r1"", r2 = ""r2"";
new Thread(() -> { synchronized(r1) { synchronized(r2) {} } }).start();
new Thread(() -> { synchronized(r2) { synchronized(r1) {} } }).start();
}",1,GEMINI,Write a Java program that results in a deadlock.,JAVA
,"public class RemoveDuplicate
{
public static void main(String[] args)
{
String input=""Welcome to Java Session Java Session Session Java"";
String[] words=input.split("" "");
for(int i=0;i<words.length;i++)
{
if(words[i]!=null)
{
for(int j=i+1;j<words.length;j++)
{
if(words[i].equals(words[j]))
{
words[j]=null;
}
}
}
}
for(int k=0;k<words.length;k++)
{
if(words[k]!=null)
{
System.out.println(words[k]);
}
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"public int trap(int[] height) {
int l = 0, r = height.length - 1, lMax = 0, rMax = 0, trapped = 0;
while (l < r) {
if (height[l] < height[r]) {
if (height[l] >= lMax) lMax = height[l]; else trapped += lMax - height[l++];
} else {
if (height[r] >= rMax) rMax = height[r]; else trapped += rMax - height[r--];
}
}
return trapped;
}",1,GEMINI,"write an effective java code for a Given elevation map (array), calculate how much water it can trap after raining. Use a two-pointer approach for $O(n)$ time and $O(1)$ space.",JAVA
,"import java.io.IOException;
public class FindTtalCountWords
{
public static void main(String args[]) throws IOException
{
countWords(""apple banna apple fruit fruit apple hello hi hi hello hi"");
}
static void countWords(String st)
{
String[] words = st.split(""\\s"");
int[] fr = new int[words.length];
for (int i = 0; i < fr.length; i++)
fr[i] = 0;
for (int i = 0; i < words.length; i++)
{
for (int j = 0; j < words.length; j++)
{
if (words[i].equals(words[j]))
{
fr[i]++;
}
}
}
for (int i = 0; i < words.length; i++)
{
for (int j = 0; j < words.length; j++)
{
if (words[i].equals(words[j]))
{
if (i != j)
{
words[i] = """";
}
}
}
}
int total = 0;
System.out.println(""Words and words count:"");
for (int i = 0; i < words.length; i++)
{
if (words[i] != """")
{
System.out.println(words[i] + ""="" + fr[i]);
total += fr[i];
}
}
System.out.println(""Total words counted: "" + total);
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"class Printer {
boolean oddTurn = true;
synchronized void print(int n, boolean isOdd) throws Exception {
while (oddTurn != isOdd) wait();
System.out.println(n);
oddTurn = !isOdd;
notifyAll();
}
}
// Logic: Thread 1 calls print(i, true), Thread 2 calls print(i, false)",1,GEMINI,Create two threads—one printing odd numbers and one even—ensuring they print in perfect sequence up to $N$.,JAVA
,"public class PalindromeChecking
{
public static void main(String[] args)
{
String inpstr =""AMMA"";
char[] inpArray = inpstr.toCharArray();
char[] revArray = new char[inpArray.length];
int j=0;
for (int i = inpArray.length - 1; i >= 0; i--) {
revArray[j]=inpArray[i];
j++;
}
String revstr=String.valueOf(revArray);
if(inpstr.equals(revstr))
{
System.out.println(""The given string is a Palindrome"");
}
else
{
System.out.println(""The given string is not a Palindrome"");
}
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"public List<String> flattenAndProcess(List<List<String>> nested) {
return nested.stream()
.flatMap(Collection::stream)
.map(String::toUpperCase)
.distinct()
.collect(Collectors.toList());
}",1,GEMINI,"Write a Java Stream pipeline to flatten a List<List<String>> into a single list of uppercase strings, removing duplicates.",JAVA
,"public class RemoveAllVovels {
public static void main(String[] args) {
String string = ""Welcome to Candid Java Programming"";
System.out.println(""Input String : ""+string);
string = string.replaceAll(""[AaEeIiOoUu]"", """");
System.out.println(string);
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int l = i + 1, r = nums.length - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum < 0) l++;
else if (sum > 0) r--;
else {
res.add(Arrays.asList(nums[i], nums[l++], nums[r--]));
while (l < r && nums[l] == nums[l-1]) l++;
}
}
}
return res;
}",1,GEMINI,Find all unique triplets in an array that sum to zero. Avoid duplicate triplets in the output.,JAVA
,"public class StringCapital
{
public static void main(String[] args)
{
String str = ""welcome to candid java program"";
StringBuilder result = new StringBuilder(str.length());
String words[] = str.split(""\\ "");
for (int i = 0; i < words.length; i++)
{
result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append
("" "");
}
System.out.println(result);
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ThreadSafeLRUCache<K, V> {
private final int capacity;
private final ConcurrentHashMap<K, Node<K, V>> cache;
private final DoublyLinkedList<K, V> dll;
private final ReentrantReadWriteLock lock;
private static class Node<K, V> {
K key;
V value;
Node<K, V> prev;
Node<K, V> next;
Node(K key, V value) {
this.key = key;
this.value = value;
}
}
private static class DoublyLinkedList<K, V> {
private Node<K, V> head;
private Node<K, V> tail;
void addToFront(Node<K, V> node) {
if (head == null) {
head = tail = node;
} else {
node.next = head;
head.prev = node;
head = node;
}
}
void remove(Node<K, V> node) {
if (node.prev != null) {
node.prev.next = node.next;
} else {
head = node.next;
}
if (node.next != null) {
node.next.prev = node.prev;
} else {
tail = node.prev;
}
node.prev = node.next = null;
}
Node<K, V> removeLast() {
if (tail == null) return null;
Node<K, V> last = tail;
remove(last);
return last;
}
void moveToFront(Node<K, V> node) {
remove(node);
addToFront(node);
}
}
public ThreadSafeLRUCache(int capacity) {
this.capacity = capacity;
this.cache = new ConcurrentHashMap<>();
this.dll = new DoublyLinkedList<>();
this.lock = new ReentrantReadWriteLock();
}
public V get(K key) {
lock.readLock().lock();
try {
Node<K, V> node = cache.get(key);
if (node == null) return null;
lock.readLock().unlock();
lock.writeLock().lock();
try {
dll.moveToFront(node);
return node.value;
} finally {
lock.readLock().lock();
lock.writeLock().unlock();
}
} finally {
lock.readLock().unlock();
}
}
public void put(K key, V value) {
lock.writeLock().lock();
try {
Node<K, V> node = cache.get(key);
if (node != null) {
node.value = value;
dll.moveToFront(node);
} else {
node = new Node<>(key, value);
if (cache.size() >= capacity) {
Node<K, V> removed = dll.removeLast();
if (removed != null) {
cache.remove(removed.key);
}
}
cache.put(key, node);
dll.addToFront(node);
}
} finally {
lock.writeLock().unlock();
}
}
public int size() {
lock.readLock().lock();
try {
return cache.size();
} finally {
lock.readLock().unlock();
}
}
}",1,DEEPSEEK,Design and implement a thread-safe Least Recently Used (LRU) cache with O(1) average time complexity for get and put operations. The cache should have a fixed capacity and evict the least recently used item when capacity is reached.,JAVA
,"public class CommaSeparated
{
public static void main(String[] args)
{
String input=""Welcome,to,Java Session Session Session"";
String[] words=input.split("","");
for(int k=0;k<words.length;k++)
{
System.out.println(words[k]);
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class TokenBucketRateLimiter {
private final long capacity;
private final long refillTokensPerSecond;
private long availableTokens;
private long lastRefillTimestamp;
private final ReentrantLock lock;
public TokenBucketRateLimiter(long capacity, long refillTokensPerSecond) {
this.capacity = capacity;
this.refillTokensPerSecond = refillTokensPerSecond;
this.availableTokens = capacity;
this.lastRefillTimestamp = System.currentTimeMillis();
this.lock = new ReentrantLock();
}
public boolean tryAcquire() {
return tryAcquire(1);
}
public boolean tryAcquire(long tokens) {
if (tokens <= 0 || tokens > capacity) {
throw new IllegalArgumentException(""Invalid token request"");
}
lock.lock();
try {
refillTokens();
if (availableTokens >= tokens) {
availableTokens -= tokens;
return true;
}
return false;
} finally {
lock.unlock();
}
}
public boolean tryAcquireWithTimeout(long tokens, long timeout, TimeUnit unit)
throws InterruptedException {
long timeoutMillis = unit.toMillis(timeout);
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < timeoutMillis) {
if (tryAcquire(tokens)) {
return true;
}
// Calculate wait time for next token
lock.lock();
try {
refillTokens();
if (availableTokens < tokens && refillTokensPerSecond > 0) {
long tokensNeeded = tokens - availableTokens;
long waitTimeMillis = (tokensNeeded * 1000) / refillTokensPerSecond;
Thread.sleep(Math.min(waitTimeMillis, 100));
}
} finally {
lock.unlock();
}
}
return false;
}
private void refillTokens() {
long now = System.currentTimeMillis();
long timeElapsed = now - lastRefillTimestamp;
if (timeElapsed > 0) {
long tokensToAdd = (timeElapsed * refillTokensPerSecond) / 1000;
if (tokensToAdd > 0) {
availableTokens = Math.min(capacity, availableTokens + tokensToAdd);
lastRefillTimestamp = now;
}
}
}
public long getAvailableTokens() {
lock.lock();
try {
refillTokens();
return availableTokens;
} finally {
lock.unlock();
}
}
}",1,DEEPSEEK,Implement a thread-safe rate limiter using the token bucket algorithm that allows a maximum of N requests per second.,JAVA
,"public class AsciiToCharacter
{
public static void main(String[] args)
{
char c;
for(int i=65;i<=90;i++)
{
c =(char)i;
System.out.println(i+"" = ""+c);
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class CircularBuffer<T> {
private final T[] buffer;
private final int capacity;
private int head;
private int tail;
private int count;
private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
private volatile boolean isShutdown;
@SuppressWarnings(""unchecked"")
public CircularBuffer(int capacity) {
this.capacity = capacity;
this.buffer = (T[]) new Object[capacity];
this.lock = new ReentrantLock();
this.notEmpty = lock.newCondition();
this.notFull = lock.newCondition();
this.isShutdown = false;
}
public boolean put(T item) throws InterruptedException {
return put(item, -1);
}
public boolean put(T item, long timeoutMillis) throws InterruptedException {
if (item == null) throw new NullPointerException();
lock.lock();
try {
// Wait until buffer is not full or shutdown
while (count == capacity && !isShutdown) {
if (timeoutMillis <= 0) {
notFull.await();
} else {
if (!notFull.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
return false;
}
}
}
if (isShutdown) return false;
buffer[tail] = item;
tail = (tail + 1) % capacity;
count++;
notEmpty.signal();
return true;
} finally {
lock.unlock();
}
}
public T take() throws InterruptedException {
return take(-1);
}
public T take(long timeoutMillis) throws InterruptedException {
lock.lock();
try {
// Wait until buffer is not empty or shutdown
while (count == 0 && !isShutdown) {
if (timeoutMillis <= 0) {
notEmpty.await();
} else {
if (!notEmpty.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
return null;
}
}
}
if (count == 0 && isShutdown) return null;
T item = buffer[head];
buffer[head] = null; // Help GC
head = (head + 1) % capacity;
count--;
notFull.signal();
return item;
} finally {
lock.unlock();
}
}
public boolean offer(T item) {
if (item == null) throw new NullPointerException();
lock.lock();
try {
if (count == capacity || isShutdown) {
return false;
}
buffer[tail] = item;
tail = (tail + 1) % capacity;
count++;
notEmpty.signal();
return true;
} finally {
lock.unlock();
}
}
public T poll() {
lock.lock();
try {
if (count == 0) {
return null;
}
T item = buffer[head];
buffer[head] = null;
head = (head + 1) % capacity;
count--;
notFull.signal();
return item;
} finally {
lock.unlock();
}
}
public int size() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
public boolean isEmpty() {
lock.lock();
try {
return count == 0;
} finally {
lock.unlock();
}
}
public boolean isFull() {
lock.lock();
try {
return count == capacity;
} finally {
lock.unlock();
}
}
public void shutdown() {
lock.lock();
try {
isShutdown = true;
notEmpty.signalAll();
notFull.signalAll();
} finally {
lock.unlock();
}
}
public void clear() {
lock.lock();
try {
for (int i = 0; i < capacity; i++) {
buffer[i] = null;
}
head = tail = count = 0;
notFull.signalAll();
} finally {
lock.unlock();
}
}
}",1,DEEPSEEK,Implement a thread-safe circular buffer (ring buffer) with fixed capacity that supports concurrent producers and consumers.,JAVA
,"public class VowelswithStar
{
public static void main(String[] args)
{
String string = ""Welcome to Candid Java Programming""; //Input String
System.out.println(""Input String : ""+string); //Displaying Input String
string = string.replaceAll(""[AaEeIiOoUu]"", ""*""); //Replace vowels with star
System.out.println(string); //Display the word after replacement
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicInteger;
public class NonBlockingStack<T> {
private static class Node<T> {
final T value;
Node<T> next;
Node(T value) {
this.value = value;
}
}
private final AtomicReference<Node<T>> top = new AtomicReference<>();
private final AtomicInteger size = new AtomicInteger(0);
private final AtomicInteger operationCount = new AtomicInteger(0);
public void push(T value) {
Node<T> newHead = new Node<>(value);
Node<T> oldHead;
do {
oldHead = top.get();
newHead.next = oldHead;
} while (!top.compareAndSet(oldHead, newHead));
size.incrementAndGet();
operationCount.incrementAndGet();
}
public T pop() {
Node<T> oldHead;
Node<T> newHead;
do {
oldHead = top.get();
if (oldHead == null) {
return null;
}
newHead = oldHead.next;
} while (!top.compareAndSet(oldHead, newHead));
size.decrementAndGet();
operationCount.incrementAndGet();
return oldHead.value;
}
public T peek() {
Node<T> currentTop = top.get();
return currentTop != null ? currentTop.value : null;
}
public boolean isEmpty() {
return top.get() == null;
}
public int size() {
return size.get();
}
public int getOperationCount() {
return operationCount.get();
}
// Optimistic traversal for size (not thread-safe for exact count)
public int optimisticSize() {
int count = 0;
Node<T> current = top.get();
while (current != null) {
count++;
current = current.next;
}
return count;
}
}",1,DEEPSEEK,Implement a thread-safe non-blocking stack using atomic operations (Treiber's algorithm).,JAVA
,"public class LetterPositionCount
{
public static void main(String args[])
{
String s = ""CANDIDJAVA"";
char[] a = s.toCharArray();
int i = 1;
{
for (char output : a)
{
System.out.print(output + "" "" + i + "" "");
i++;
}
}
}
} ",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class CustomThreadPool {
private final BlockingQueue<Runnable> taskQueue;
private final WorkerThread[] workers;
private volatile boolean isShutdown;
private final ReentrantLock mainLock = new ReentrantLock();
private final Condition termination = mainLock.newCondition();
private final AtomicInteger activeWorkers = new AtomicInteger(0);
private final ThreadFactory threadFactory;
private class WorkerThread extends Thread {
private volatile Runnable currentTask;
private volatile boolean stopped;
public WorkerThread(String name) {
super(name);
}
@Override
public void run() {
activeWorkers.incrementAndGet();
try {
while (!stopped && !isShutdown) {
try {
// Poll with timeout to allow graceful shutdown
Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS);
if (task != null) {
currentTask = task;
try {
task.run();
} catch (RuntimeException e) {
System.err.println(""Task execution failed: "" + e.getMessage());
} finally {
currentTask = null;
}
}
} catch (InterruptedException e) {
// Thread interrupted, check if we should exit
if (stopped || isShutdown) {
break;
}
}
}
} finally {
activeWorkers.decrementAndGet();
signalIfTerminated();
}
}
public void stopWorker() {
this.stopped = true;
this.interrupt();
}
public Runnable getCurrentTask() {
return currentTask;
}
}
public CustomThreadPool(int poolSize) {
this(poolSize, Executors.defaultThreadFactory());
}
public CustomThreadPool(int poolSize, ThreadFactory threadFactory) {
if (poolSize <= 0) {
throw new IllegalArgumentException(""Pool size must be positive"");
}
this.taskQueue = new LinkedBlockingQueue<>();
this.workers = new WorkerThread[poolSize];
this.threadFactory = threadFactory;
this.isShutdown = false;
// Initialize workers
for (int i = 0; i < poolSize; i++) {
WorkerThread worker = new WorkerThread(""CustomPool-Worker-"" + i);
workers[i] = worker;
worker.start();
}
}
public void execute(Runnable task) {
if (task == null) throw new NullPointerException();
if (isShutdown) throw new RejectedExecutionException(""Thread pool is shutdown"");
try {
taskQueue.put(task);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RejectedExecutionException(""Interrupted while submitting task"", e);
}
}
public Future<?> submit(Runnable task) {
FutureTask<Void> future = new FutureTask<>(task, null);
execute(future);
return future;
}
public <T> Future<T> submit(Callable<T> task) {
FutureTask<T> future = new FutureTask<>(task);
execute(future);
return future;
}
public void shutdown() {
mainLock.lock();
try {
isShutdown = true;
} finally {
mainLock.unlock();
}
}
public void shutdownNow() {
mainLock.lock();
try {
isShutdown = true;
// Clear task queue
taskQueue.clear();
// Interrupt all workers
for (WorkerThread worker : workers) {
if (worker != null) {
worker.stopWorker();
}
}
} finally {
mainLock.unlock();
}
}
public boolean isShutdown() {
return isShutdown;
}
public boolean isTerminated() {
return isShutdown && activeWorkers.get() == 0 && taskQueue.isEmpty();
}
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
mainLock.lock();
try {
while (!isTerminated()) {
if (nanos <= 0) {
return false;
}
nanos = termination.awaitNanos(nanos);
}
return true;
} finally {
mainLock.unlock();
}
}
public int getActiveCount() {
return activeWorkers.get();
}
public int getPoolSize() {
return workers.length;
}
public long getTaskCount() {
return taskQueue.size();
}
private void signalIfTerminated() {
mainLock.lock();
try {
if (isTerminated()) {
termination.signalAll();
}
} finally {
mainLock.unlock();
}
}
}",1,DEEPSEEK,"Implement a custom thread pool executor with fixed thread count, task queue, and shutdown capabilities.",JAVA
,"public class ReverseWord
{
public static void main(String[] args)
{
String input=""Welcome to Java Session"";
String[] words=input.split("" "");
String[] revwords=new String[words.length];
int j=0;
for(int i=words.length-1;i>=0;i--)
{
revwords[j]=words[i];
System.out.print(revwords[j]+"" "");
j++;
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
public class WriterPreferenceReadWriteLock implements ReadWriteLock {
private final Sync sync;
public WriterPreferenceReadWriteLock() {
this.sync = new Sync();
}
private static class Sync extends AbstractQueuedSynchronizer {
private static final int READER_MASK = (1 << 16) - 1;
private static final int WRITER_MASK = ~READER_MASK;
private int readers() {
return getState() & READER_MASK;
}
private int writers() {
return (getState() >>> 16) & READER_MASK;
}
private int incrementReaders() {
return getState() + 1;
}
private int decrementReaders() {
return getState() - 1;
}
private int incrementWriters() {
return getState() + (1 << 16);
}
private int decrementWriters() {
return getState() - (1 << 16);
}
@Override
protected boolean tryAcquire(int arg) {
Thread current = Thread.currentThread();
int state = getState();
// If no readers or writers, try to acquire write lock
if (state == 0) {
if (compareAndSetState(0, 1 << 16)) {
setExclusiveOwnerThread(current);
return true;
}
} else if (getExclusiveOwnerThread() == current) {
// Reentrant write lock
setState(state + (1 << 16));
return true;
}
return false;
}
@Override
protected boolean tryRelease(int arg) {
if (getExclusiveOwnerThread() != Thread.currentThread()) {
throw new IllegalMonitorStateException();
}
int newState = decrementWriters();
boolean free = (newState & WRITER_MASK) == 0;
if (free) {
setExclusiveOwnerThread(null);
}
setState(newState);
return free;
}
@Override
protected int tryAcquireShared(int arg) {
Thread current = Thread.currentThread();
int state = getState();
// If there are waiting writers, don't acquire read lock
if (hasQueuedPredecessors()) {
return -1;
}
// If no writers, try to acquire read lock
if ((state & WRITER_MASK) == 0) {
if (compareAndSetState(state, incrementReaders())) {
return 1;
}
}
return -1;
}
@Override
protected boolean tryReleaseShared(int arg) {
int newState;
int currentState;
do {
currentState = getState();
newState = decrementReaders();
} while (!compareAndSetState(currentState, newState));
return true;
}
@Override
protected boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
Condition newCondition() {
return new ConditionObject();
}
}
private static class ReadLock implements Lock {
private final Sync sync;
ReadLock(Sync sync) {
this.sync = sync;
}
@Override
public void lock() {
sync.acquireShared(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryAcquireShared(1) >= 0;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.releaseShared(1);
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException(""Read locks don't support conditions"");
}
}
private static class WriteLock implements Lock {
private final Sync sync;
WriteLock(Sync sync) {
this.sync = sync;
}
@Override
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryAcquire(1);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.release(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
}
@Override
public Lock readLock() {
return new ReadLock(sync);
}
@Override
public Lock writeLock() {
return new WriteLock(sync);
}
}",1,DEEPSEEK,Implement a read-write lock that gives preference to writers to prevent writer starvation.,JAVA
,"public class StringReverse {
public static void main(String args[])
{
String string = ""Welcome to Java Programming and Dotnet Programming"";
String[] wordsCount = string.split("" "");
System.out.println(""The Given String is:\n"" + string + ""\n"");
System.out.println(""After Reverse String is:"");
for(int i = wordsCount.length;i > 0;i--)
{
System.out.print(wordsCount[i - 1] + "" "");
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
public class DistributedTaskScheduler {
private final ExecutorService executor;
private final List<WorkerNode> workerNodes;
private final Map<String, ScheduledTask> tasks;
private final AtomicInteger taskIdCounter;
private final ReentrantLock lock;
private final ScheduledExecutorService healthCheckScheduler;
public static class WorkerNode {
private final String id;
private final String host;
private final int port;
private volatile boolean healthy;
private volatile long lastHeartbeat;
public WorkerNode(String id, String host, int port) {
this.id = id;
this.host = host;
this.port = port;
this.healthy = true;
this.lastHeartbeat = System.currentTimeMillis();
}
// Getters and setters
public String getId() { return id; }
public String getHost() { return host; }
public int getPort() { return port; }
public boolean isHealthy() { return healthy; }
public void setHealthy(boolean healthy) { this.healthy = healthy; }
public long getLastHeartbeat() { return lastHeartbeat; }
public void updateHeartbeat() { this.lastHeartbeat = System.currentTimeMillis(); }
}
public static class ScheduledTask {
private final String id;
private final Runnable task;
private final long initialDelay;
private final long period;
private final TimeUnit timeUnit;
private volatile TaskStatus status;
private volatile String assignedWorker;
private volatile Future<?> future;
public ScheduledTask(String id, Runnable task, long initialDelay,
long period, TimeUnit timeUnit) {
this.id = id;
this.task = task;
this.initialDelay = initialDelay;
this.period = period;
this.timeUnit = timeUnit;
this.status = TaskStatus.PENDING;
}
public enum TaskStatus {
PENDING, SCHEDULED, RUNNING, COMPLETED, FAILED, CANCELLED
}
// Getters and setters
public String getId() { return id; }
public Runnable getTask() { return task; }
public long getInitialDelay() { return initialDelay; }
public long getPeriod() { return period; }
public TimeUnit getTimeUnit() { return timeUnit; }
public TaskStatus getStatus() { return status; }
public void setStatus(TaskStatus status) { this.status = status; }
public String getAssignedWorker() { return assignedWorker; }
public void setAssignedWorker(String workerId) { this.assignedWorker = workerId; }
public Future<?> getFuture() { return future; }
public void setFuture(Future<?> future) { this.future = future; }
}
public DistributedTaskScheduler(int corePoolSize) {
this.executor = Executors.newFixedThreadPool(corePoolSize);
this.workerNodes = new CopyOnWriteArrayList<>();
this.tasks = new ConcurrentHashMap<>();
this.taskIdCounter = new AtomicInteger(0);
this.lock = new ReentrantLock();
this.healthCheckScheduler = Executors.newScheduledThreadPool(1);
// Start health check
startHealthCheck();
}
private void startHealthCheck() {
healthCheckScheduler.scheduleAtFixedRate(() -> {
checkWorkerHealth();
reassignFailedTasks();
}, 30, 30, TimeUnit.SECONDS);
}
private void checkWorkerHealth() {
long currentTime = System.currentTimeMillis();
long threshold = currentTime - 60000; // 1 minute timeout
for (WorkerNode worker : workerNodes) {
if (worker.getLastHeartbeat() < threshold) {
worker.setHealthy(false);
System.err.println(""Worker "" + worker.getId() + "" marked as unhealthy"");
}
}
}
private void reassignFailedTasks() {
lock.lock();
try {
for (ScheduledTask task : tasks.values()) {
if (task.getStatus() == ScheduledTask.TaskStatus.RUNNING) {
WorkerNode assignedWorker = findWorkerById(task.getAssignedWorker());
if (assignedWorker == null || !assignedWorker.isHealthy()) {
// Task is running on failed worker, reschedule
rescheduleTask(task);
}
}
}
} finally {
lock.unlock();
}
}
private void rescheduleTask(ScheduledTask task) {
task.setStatus(ScheduledTask.TaskStatus.PENDING);
task.setAssignedWorker(null);
if (task.getFuture() != null) {
task.getFuture().cancel(false);
}
scheduleTask(task);
}
private WorkerNode findWorkerById(String workerId) {
if (workerId == null) return null;
for (WorkerNode worker : workerNodes) {
if (worker.getId().equals(workerId)) {
return worker;
}
}
return null;
}
public void registerWorker(WorkerNode worker) {
workerNodes.add(worker);
System.out.println(""Registered worker: "" + worker.getId());
}
public void unregisterWorker(String workerId) {
workerNodes.removeIf(worker -> worker.getId().equals(workerId));
// Reassign tasks from removed worker
reassignFailedTasks();
}
public String scheduleTask(Runnable task, long initialDelay,
long period, TimeUnit unit) {
String taskId = ""task-"" + taskIdCounter.incrementAndGet();
ScheduledTask scheduledTask = new ScheduledTask(taskId, task,
initialDelay, period, unit);
tasks.put(taskId, scheduledTask);
scheduleTask(scheduledTask);
return taskId;
}
private void scheduleTask(ScheduledTask scheduledTask) {
WorkerNode worker = selectWorker();
if (worker == null)",1,DEEPSEEK,Design a task scheduler that can distribute tasks across multiple worker nodes and handle failures.,JAVA
,"import java.util.Scanner;
class MinMaxInArray
{
int getMax(int[]inputArray)
{
int maxValue=inputArray[0];
for(int i=1;i<inputArray.length;i++)
{
if(inputArray[i]>maxValue)
{
maxValue=inputArray[i];
}
}
return maxValue;
}
int getMin(int[]inputArray)
{
int minValue=inputArray[0];
for(int i=1;i<inputArray.length;i++)
{
if(inputArray[i]<minValue)
{
minValue=inputArray[i];
}
}
return minValue;
}
}
public class ExArrayDifference
{
public static void main(String[] args)
{
int n;
Scanner sc = new Scanner(System.in);
System.out.print(""Enter number of elements you wants to enter :"" );
n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<arr.length;i++)
{
System.out.print(""Enter [""+(i+1)+""] element :"" );
arr[i]=sc.nextInt();
}
MinMaxInArray mm=new MinMaxInArray();
System.out.println(""Maximum value is :"" +mm.getMax(arr));
System.out.println(""Minimum value is :"" +mm.getMin(arr));
int Difference=mm.getMax(arr)-mm.getMin(arr);
System.out.print(""Difference between Minnimum and Maximum in array is : ""
+Difference );
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SlidingWindowRateLimiter {
private final int maxRequests;
private final long windowMillis;
private final ConcurrentHashMap<String, Window> userWindows;
private static class Window {
final ConcurrentLinkedQueue<Long> timestamps;
final AtomicInteger currentRequests;
Window() {
this.timestamps = new ConcurrentLinkedQueue<>();
this.currentRequests = new AtomicInteger(0);
}
}
public SlidingWindowRateLimiter(int maxRequests, long windowDuration, TimeUnit timeUnit) {
this.maxRequests = maxRequests;
this.windowMillis = timeUnit.toMillis(windowDuration);
this.userWindows = new ConcurrentHashMap<>();
}
public boolean allowRequest(String userId) {
Window window = userWindows.computeIfAbsent(userId, k -> new Window());
long currentTime = System.currentTimeMillis();
long cutoffTime = currentTime - windowMillis;
// Clean old timestamps
while (!window.timestamps.isEmpty() &&
window.timestamps.peek() < cutoffTime) {
window.timestamps.poll();
window.currentRequests.decrementAndGet();
}
// Check if under limit
if (window.currentRequests.get() >= maxRequests) {
return false;
}
// Add new request
window.timestamps.offer(currentTime);
window.currentRequests.incrementAndGet();
return true;
}
public void reset(String userId) {
userWindows.remove(userId);
}
}",1,DEEPSEEK,Create a rate limiter that allows N requests per minute with sliding window algorithm.,JAVA
,"class NoOfOccurenceOfCharacters
{
static final int MAX_CHAR = 256;
static void getOccuringChar(String str)
{
int count[] = new int[MAX_CHAR];
int len = str.length();
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
char ch[] = new char[str.length()];
for (int i = 0; i < len; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println(""Number of Occurrence of "" +
str.charAt(i) + "" is:"" + count[str.charAt(i)]);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = ""geeksforgeeks"";
getOccuringChar(str);
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
public class RetryExecutor {
private final int maxAttempts;
private final Duration initialDelay;
private final Duration maxDelay;
private final double backoffMultiplier;
private final Predicate<Exception> retryPredicate;
private RetryExecutor(Builder builder) {
this.maxAttempts = builder.maxAttempts;
this.initialDelay = builder.initialDelay;
this.maxDelay = builder.maxDelay;
this.backoffMultiplier = builder.backoffMultiplier;
this.retryPredicate = builder.retryPredicate;
}
public <T> T execute(Callable<T> task) throws Exception {
Exception lastException = null;
Duration currentDelay = initialDelay;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return task.call();
} catch (Exception e) {
lastException = e;
if (attempt == maxAttempts || !shouldRetry(e)) {
throw e;
}
if (attempt < maxAttempts) {
sleepWithJitter(currentDelay);
currentDelay = calculateNextDelay(currentDelay);
}
}
}
throw lastException;
}
private boolean shouldRetry(Exception e) {
return retryPredicate == null || retryPredicate.test(e);
}
private void sleepWithJitter(Duration delay) {
try {
long jitter = ThreadLocalRandom.current().nextLong(
(long) (delay.toMillis() * 0.1)
);
Thread.sleep(delay.toMillis() + jitter);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(""Retry interrupted"", e);
}
}
private Duration calculateNextDelay(Duration currentDelay) {
long nextDelayMillis = (long) (currentDelay.toMillis() * backoffMultiplier);
if (nextDelayMillis > maxDelay.toMillis()) {
nextDelayMillis = maxDelay.toMillis();
}
return Duration.ofMillis(nextDelayMillis);
}
public static class Builder {
private int maxAttempts = 3;
private Duration initialDelay = Duration.ofMillis(100);
private Duration maxDelay = Duration.ofSeconds(30);
private double backoffMultiplier = 2.0;
private Predicate<Exception> retryPredicate;
public Builder maxAttempts(int maxAttempts) {
this.maxAttempts = maxAttempts;
return this;
}
public Builder initialDelay(Duration initialDelay) {
this.initialDelay = initialDelay;
return this;
}
public Builder maxDelay(Duration maxDelay) {
this.maxDelay = maxDelay;
return this;
}
public Builder backoffMultiplier(double backoffMultiplier) {
this.backoffMultiplier = backoffMultiplier;
return this;
}
public Builder retryOn(Predicate<Exception> retryPredicate) {
this.retryPredicate = retryPredicate;
return this;
}
public RetryExecutor build() {
return new RetryExecutor(this);
}
}
}",1,DEEPSEEK,Create a retry mechanism that handles transient failures with exponential backoff.,JAVA
,"// Define the Cat class
public class Cat {
// Private instance variables
private String name;
private int age;
// Default constructor
public Cat() {
// Initialize name to ""Unknown""
this.name = ""Unknown"";
// Initialize age to 0
this.age = 0;
}
// Getter for name
public String getName() {
return name;
}
// Getter for age
public int getAge() {
return age;
}
// Main method to test the Cat class
public static void main(String[] args) {
// Create a new Cat object using the default constructor
Cat myCat = new Cat();
// Use the getter methods to access private variables
System.out.println(""Cat's Name: "" + myCat.getName());
System.out.println(""Cat's Age: "" + myCat.getAge());
}
} ",0,WE3RESOURCE,NA,JAVA
,"import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class DatabaseConnectionPool {
private final BlockingQueue<PooledConnection> availableConnections;
private final AtomicInteger activeConnections = new AtomicInteger(0);
private final int maxPoolSize;
private final String url;
private final String username;
private final String password;
private volatile boolean isClosed = false;
public DatabaseConnectionPool(String url, String username,
String password, int maxPoolSize) {
this.url = url;
this.username = username;
this.password = password;
this.maxPoolSize = maxPoolSize;
this.availableConnections = new LinkedBlockingQueue<>(maxPoolSize);
initializePool();
}
private void initializePool() {
for (int i = 0; i < maxPoolSize / 2; i++) {
try {
availableConnections.offer(createConnection());
} catch (SQLException e) {
throw new RuntimeException(""Failed to initialize connection pool"", e);
}
}
}
private PooledConnection createConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, username, password);
return new PooledConnection(connection, this);
}
public Connection getConnection() throws SQLException {
return getConnection(30, TimeUnit.SECONDS);
}
public Connection getConnection(long timeout, TimeUnit unit) throws SQLException {
if (isClosed) {
throw new SQLException(""Connection pool is closed"");
}
try {
// Try to get existing connection
PooledConnection pooledConn = availableConnections.poll(timeout, unit);
if (pooledConn != null) {
if (!pooledConn.getConnection().isValid(2)) {
closeQuietly(pooledConn.getConnection());
pooledConn = createConnection();
}
activeConnections.incrementAndGet();
return pooledConn;
}
// Create new connection if pool not full
if (activeConnections.get() < maxPoolSize) {
PooledConnection newConn = createConnection();
activeConnections.incrementAndGet();
return newConn;
}
throw new SQLException(""Connection pool exhausted"");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new SQLException(""Interrupted while waiting for connection"");
}
}
void returnConnection(PooledConnection connection) {
if (isClosed) {
closeQuietly(connection.getConnection());
return;
}
try {
if (connection.getConnection().isClosed() ||
!connection.getConnection().isValid(2)) {
closeQuietly(connection.getConnection());
availableConnections.offer(createConnection());
} else {
availableConnections.offer(connection);
}
} catch (SQLException e) {
// Connection is invalid, create new one
closeQuietly(connection.getConnection());
try {
availableConnections.offer(createConnection());
} catch (SQLException ex) {
// Log error but don't throw
}
} finally {
activeConnections.decrementAndGet();
}
}
public void close() {
isClosed = true;
availableConnections.forEach(conn ->
closeQuietly(conn.getConnection())
);
availableConnections.clear();
}
public int getActiveConnections() {
return activeConnections.get();
}
public int getIdleConnections() {
return availableConnections.size();
}
private void closeQuietly(Connection connection) {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
// Ignore
}
}
private class PooledConnection extends ConnectionWrapper {
private final DatabaseConnectionPool pool;
PooledConnection(Connection connection, DatabaseConnectionPool pool) {
super(connection);
this.pool = pool;
}
@Override
public void close() throws SQLException {
pool.returnConnection(this);
}
}
private abstract class ConnectionWrapper implements Connection {
protected final Connection delegate;
ConnectionWrapper(Connection delegate) {
this.delegate = delegate;
}
// Delegate all Connection methods to the wrapped connection
@Override
public Statement createStatement() throws SQLException {
return delegate.createStatement();
}
// ... implement all other Connection methods similarly
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(delegate) || delegate.isWrapperFor(iface);
}
@SuppressWarnings(""unchecked"")
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(delegate)) {
return (T) delegate;
}
return delegate.unwrap(iface);
}
}
}",1,DEEPSEEK,Create a generic connection pool for managing database connections.,JAVA
,"// Define the Dog class
public class Dog {
// Private instance variables
private String name;
private String color;
// Parameterized constructor
public Dog(String name, String color) {
// Initialize name with the provided parameter
this.name = name;
// Initialize color with the provided parameter
this.color = color;
}
// Main method to test the Dog class
public static void main(String[] args) {
// Create a new Dog object using the parameterized constructor
Dog myDog = new Dog(""Bailey"", ""Black"");
// Print the values of the instance variables
System.out.println(""Dog's Name: "" + myDog.name);
System.out.println(""Dog's Color: "" + myDog.color);
}
} ",0,WE3RESOURCE,NA,JAVA
,"import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
public class EventStore {
private final ConcurrentHashMap<String, List<Event>> streams;
private final ConcurrentHashMap<String, AtomicLong> streamVersions;
public EventStore() {
this.streams = new ConcurrentHashMap<>();
this.streamVersions = new ConcurrentHashMap<>();
}
public static class Event {
private final String eventId;
private final String streamId;
private final String eventType;
private final Map<String, Object> data;
private final Map<String, Object> metadata;
private final Instant timestamp;
private final long version;
public Event(String streamId, String eventType,
Map<String, Object> data, long version) {
this.eventId = UUID.randomUUID().toString();
this.streamId = streamId;
this.eventType = eventType;
this.data = Collections.unmodifiableMap(new HashMap<>(data));
this.metadata = new HashMap<>();
this.timestamp = Instant.now();
this.version = version;
}
// Getters
public String getEventId() { return eventId; }
public String getStreamId() { return streamId; }
public String getEventType() { return eventType; }
public Map<String, Object> getData() { return data; }
public Map<String, Object> getMetadata() { return metadata; }
public Instant getTimestamp() { return timestamp; }
public long getVersion() { return version; }
public void addMetadata(String key, Object value) {
metadata.put(key, value);
}
}
public AppendResult appendToStream(String streamId, List<Event> events,
long expectedVersion) {
if (events == null || events.isEmpty()) {
throw new IllegalArgumentException(""Events cannot be empty"");
}
streams.compute(streamId, (key, existingEvents) -> {
long currentVersion = streamVersions
.computeIfAbsent(streamId, k -> new AtomicLong(0))
.get();
// Optimistic concurrency check
if (expectedVersion != -1 && currentVersion != expectedVersion) {
throw new ConcurrencyException(
String.format(""Expected version %d but was %d"",
expectedVersion, currentVersion)
);
}
List<Event> streamEvents = existingEvents != null ?
new ArrayList<>(existingEvents) : new ArrayList<>();
// Assign versions to events
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Event versionedEvent = new Event(
streamId,
event.eventType,
event.data,
currentVersion + i + 1
);
event.metadata.forEach(versionedEvent::addMetadata);
streamEvents.add(versionedEvent);
}
// Update version
streamVersions.get(streamId).addAndGet(events.size());
return Collections.unmodifiableList(streamEvents);
});
return new AppendResult(streamId,
streamVersions.get(streamId).get(),
events.size()
);
}
public List<Event> readStream(String streamId) {
List<Event> events = streams.get(streamId);
return events != null ? new ArrayList<>(events) : new ArrayList<>();
}
public List<Event> readStream(String streamId, long fromVersion) {
List<Event> events = streams.get(streamId);
if (events == null) {
return new ArrayList<>();
}
return events.stream()
.filter(e -> e.getVersion() >= fromVersion)
.collect(Collectors.toList());
}
public List<Event> readAllEvents() {
return streams.values().stream()
.flatMap(List::stream)
.sorted(Comparator.comparing(Event::getTimestamp)
.thenComparing(Event::getVersion))
.collect(Collectors.toList());
}
public long getStreamVersion(String streamId) {
AtomicLong version = streamVersions.get(streamId);
return version != null ? version.get() : 0;
}
public void subscribe(EventSubscriber subscriber) {
// Implementation for event subscription
}
public static class AppendResult {
private final String streamId;
private final long newVersion;
private final int eventsAppended;
AppendResult(String streamId, long newVersion, int eventsAppended) {
this.streamId = streamId;
this.newVersion = newVersion;
this.eventsAppended = eventsAppended;
}
public String getStreamId() { return streamId; }
public long getNewVersion() { return newVersion; }
public int getEventsAppended() { return eventsAppended; }
}
public interface EventSubscriber {
void handle(Event event);
}
public static class ConcurrencyException extends RuntimeException {
public ConcurrencyException(String message) {
super(message);
}
}
}",1,DEEPSEEK,Create an event store for CQRS pattern with optimistic concurrency control.,JAVA
,"// Define the Book class
public class Book {
// Private instance variables
private String title;
private String author;
private double price;
// Default constructor
public Book() {
// Initialize title to ""Unknown""
this.title = ""Unknown"";
// Initialize author to ""Unknown""
this.author = ""Unknown"";
// Initialize price to 0.0
this.price = 0.0;
}
// Parameterized constructor (title, author)
public Book(String title, String author) {
// Initialize title with the provided parameter
this.title = title;
// Initialize author with the provided parameter
this.author = author;
// Initialize price to 0.0
this.price = 0.0;
}
// Parameterized constructor (title, author, price)
public Book(String title, String author, double price) {
// Initialize title with the provided parameter
this.title = title;
// Initialize author with the provided parameter
this.author = author;
// Initialize price with the provided parameter
this.price = price;
}
// Main method to test the Book class
public static void main(String[] args) {
// Create a new Book object using the default constructor
Book book1 = new Book();
// Print the values of the instance variables for book1
System.out.println(""Book1 Title: "" + book1.title);
System.out.println(""Book1 Author: "" + book1.author);
System.out.println(""Book1 Price: "" + book1.price);
// Create a new Book object using the parameterized constructor (title, author)
Book book2 = new Book(""Amatka"", ""Karin Tidbeck"");
// Print the values of the instance variables for book2
System.out.println(""Book2 Title: "" + book2.title);
System.out.println(""Book2 Author: "" + book2.author);
System.out.println(""Book2 Price: "" + book2.price);
// Create a new Book object using the parameterized constructor (title, author, price)
Book book3 = new Book(""Altered Carbon"", ""Richard K. Morgan"", 18.99);
// Print the values of the instance variables for book3
System.out.println(""Book3 Title: "" + book3.title);
System.out.println(""Book3 Author: "" + book3.author);
System.out.println(""Book3 Price: "" + book3.price);
}
} ",0,WE3RESOURCE,NA,JAVA
,"import java.time.Instant;
import java.util.concurrent.atomic.AtomicLong;
public class SnowflakeIdGenerator {
private static final long EPOCH = 1609459200000L; // 2021-01-01
private static final long WORKER_ID_BITS = 5L;
private static final long DATACENTER_ID_BITS = 5L;
private static final long SEQUENCE_BITS = 12L;
private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;
private static final long MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) - 1;
private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
private final long workerId;
private final long datacenterId;
private final AtomicLong sequence = new AtomicLong(0);
private volatile long lastTimestamp = -1L;
public SnowflakeIdGenerator(long workerId, long datacenterId) {
if (workerId > MAX_WORKER_ID || workerId < 0) {
throw new IllegalArgumentException(
String.format(""Worker ID must be between 0 and %d"", MAX_WORKER_ID)
);
}
if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
throw new IllegalArgumentException(
String.format(""Datacenter ID must be between 0 and %d"", MAX_DATACENTER_ID)
);
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public synchronized long nextId() {
long timestamp = currentTimestamp();
if (timestamp < lastTimestamp) {
throw new IllegalStateException(
String.format(""Clock moved backwards. Refusing to generate ID for %d milliseconds"",
lastTimestamp - timestamp)
);
}
if (timestamp == lastTimestamp) {
long currentSequence = (sequence.incrementAndGet() & MAX_SEQUENCE);
if (currentSequence == 0) {
// Sequence overflow, wait for next millisecond
timestamp = waitNextMillis(lastTimestamp);
}
} else {
sequence.set(0);
}
lastTimestamp = timestamp;
return ((timestamp - EPOCH) << TIMESTAMP_SHIFT) |
(datacenterId << DATACENTER_ID_SHIFT) |
(workerId << WORKER_ID_SHIFT) |
sequence.get();
}
public String nextIdAsString() {
return Long.toString(nextId());
}
public Instant getTimestampFromId(long id) {
long timestamp = (id >> TIMESTAMP_SHIFT) + EPOCH;
return Instant.ofEpochMilli(timestamp);
}
public long getWorkerIdFromId(long id) {
return (id >> WORKER_ID_SHIFT) & MAX_WORKER_ID;
}
public long getDatacenterIdFromId(long id) {
return (id >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID;
}
public long getSequenceFromId(long id) {
return id & MAX_SEQUENCE;
}
private long waitNextMillis(long lastTimestamp) {
long timestamp = currentTimestamp();
while (timestamp <= lastTimestamp) {
timestamp = currentTimestamp();
}
return timestamp;
}
private long currentTimestamp() {
return System.currentTimeMillis();
}
public static class IdMetadata {
private final long id;
private final Instant timestamp;
private final long workerId;
private final long datacenterId;
private final long sequence;
public IdMetadata(long id) {
this.id = id;
SnowflakeIdGenerator generator = new SnowflakeIdGenerator(0, 0);
this.timestamp = generator.getTimestampFromId(id);
this.workerId = generator.getWorkerIdFromId(id);
this.datacenterId = generator.getDatacenterIdFromId(id);
this.sequence = generator.getSequenceFromId(id);
}
// Getters
public long getId() { return id; }
public Instant getTimestamp() { return timestamp; }
public long getWorkerId() { return workerId; }
public long getDatacenterId() { return datacenterId; }
public long getSequence() { return sequence; }
@Override
public String toString() {
return String.format(
""ID: %d, Timestamp: %s, Worker: %d, Datacenter: %d, Sequence: %d"",
id, timestamp, workerId, datacenterId, sequence
);
}
}
}",1,DEEPSEEK,Create a distributed unique ID generator similar to Twitter's Snowflake.,JAVA
,"// Define the Student class
public class Student {
// Private instance variables
private int studentId;
private String studentName;
private String grade;
// Default constructor
public Student() {
// Call the parameterized constructor with default values
this(0, ""Unknown"", ""None"");
}
// Parameterized constructor
public Student(int studentId, String studentName, String grade) {
// Initialize studentId with the provided parameter
this.studentId = studentId;
// Initialize studentName with the provided parameter
this.studentName = studentName;
// Initialize grade with the provided parameter
this.grade = grade;
}
// Main method to test the Student class
public static void main(String[] args) {
// Create a new Student object using the default constructor
Student student1 = new Student();
// Print the values of the instance variables for student1
System.out.println(""Student1 ID: "" + student1.studentId);
System.out.println(""Student1 Name: "" + student1.studentName);
System.out.println(""Student1 Grade: "" + student1.grade);
// Create a new Student object using the parameterized constructor
Student student2 = new Student(101, ""Cullen"", ""A"");
// Print the values of the instance variables for student2
System.out.println(""Student2 ID: "" + student2.studentId);
System.out.println(""Student2 Name: "" + student2.studentName);
System.out.println(""Student2 Grade: "" + student2.grade);
}
} ",0,WE3RESOURCE,NA,JAVA
,"import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class PriorityMessageQueue<T> {
private final PriorityQueue<Message<T>> queue;
private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
private final int maxCapacity;
private volatile boolean shutdown;
public enum Priority {
HIGH, MEDIUM, LOW
}
private static class Message<T> {
final T payload;
final Priority priority;
final long timestamp;
final String messageId;
int deliveryAttempts;
Message(T payload, Priority priority) {
this.payload = payload;
this.priority = priority;
this.timestamp = System.currentTimeMillis();
this.messageId = java.util.UUID.randomUUID().toString();
this.deliveryAttempts = 0;
}
long getPriorityScore() {
long priorityMultiplier;
switch (priority) {
case HIGH: priorityMultiplier = 1000; break;
case MEDIUM: priorityMultiplier = 100; break;
default: priorityMultiplier = 1;
}
return timestamp / priorityMultiplier;
}
}
private static class MessageComparator<T> implements Comparator<Message<T>> {
@Override
public int compare(Message<T> m1, Message<T> m2) {
return Long.compare(m1.getPriorityScore(), m2.getPriorityScore());
}
}
public PriorityMessageQueue(int maxCapacity) {
this.maxCapacity = maxCapacity;
this.queue = new PriorityQueue<>(new MessageComparator<>());
this.lock = new ReentrantLock();
this.notEmpty = lock.newCondition();
this.notFull = lock.newCondition();
this.shutdown = false;
}
public boolean enqueue(T payload, Priority priority) {
return enqueue(payload, priority, -1, TimeUnit.MILLISECONDS);
}
public boolean enqueue(T payload, Priority priority,
long timeout, TimeUnit unit) {
if (payload == null) throw new NullPointerException();
if (shutdown) throw new IllegalStateException(""Queue is shutdown"");
lock.lock();
try {
long nanos = unit.toNanos(timeout);
while (queue.size() >= maxCapacity && !shutdown) {
if (nanos <= 0) {
return false;
}
nanos = notFull.awaitNanos(nanos);
}
if (shutdown) return false;
Message<T> message = new Message<>(payload, priority);
queue.offer(message);
notEmpty.signal();
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
lock.unlock();
}
}
public Message<T> dequeue() throws InterruptedException {
return dequeue(-1, TimeUnit.MILLISECONDS);
}
public Message<T> dequeue(long timeout, TimeUnit unit)
throws InterruptedException {
lock.lock();
try {
long nanos = unit.toNanos(timeout);
while (queue.isEmpty() && !shutdown) {
if (nanos <= 0) {
return null;
}
nanos = notEmpty.awaitNanos(nanos);
}
if (queue.isEmpty() && shutdown) {
return null;
}
Message<T> message = queue.poll();
notFull.signal();
if (message != null) {
message.deliveryAttempts++;
}
return message;
} finally {
lock.unlock();
}
}
public void acknowledge(String messageId) {
// In a real implementation, this would track delivery status
// For simplicity, we just remove from queue
lock.lock();
try {
queue.removeIf(msg -> msg.messageId.equals(messageId));
notFull.signal();
} finally {
lock.unlock();
}
}
public void requeue(Message<T> message) {
lock.lock();
try {
if (message.deliveryAttempts < 3) {
queue.offer(message);
notEmpty.signal();
} else {
// Move to dead letter queue or log
System.err.println(""Message "" + message.messageId +
"" exceeded max delivery attempts"");
}
} finally {
lock.unlock();
}
}
public int size() {
lock.lock();
try {
return queue.size();
} finally {
lock.unlock();
}
}
public boolean isEmpty() {
lock.lock();
try {
return queue.isEmpty();
} finally {
lock.unlock();
}
}
public void shutdown() {
lock.lock();
try {
shutdown = true;
notEmpty.signalAll();
notFull.signalAll();
} finally {
lock.unlock();
}
}
public void clear() {
lock.lock();
try {
queue.clear();
notFull.signalAll();
} finally {
lock.unlock();
}
}
}",1,DEEPSEEK,Create a thread-safe message queue with priority levels and delivery guarantees.,JAVA
,"// Define the Rectangle class
public class Rectangle {
// Private instance variables
private double length;
private double width;
// Parameterized constructor
public Rectangle(double length, double width) {
// Initialize length with the provided parameter
this.length = length;
// Initialize width with the provided parameter
this.width = width;
}
// Copy constructor
public Rectangle(Rectangle rectangle) {
// Initialize length with the length of the provided rectangle object
this.length = rectangle.length;
// Initialize width with the width of the provided rectangle object
this.width = rectangle.width;
}
// Main method to test the Rectangle class
public static void main(String[] args) {
// Create a new Rectangle object using the parameterized constructor
Rectangle rect1 = new Rectangle(12.5, 4.5);
// Print the values of the instance variables for rect1
System.out.println(""Rectangle 1 Length: "" + rect1.length);
System.out.println(""Rectangle 1 Width: "" + rect1.width);
// Create a new Rectangle object using the copy constructor
Rectangle rect2 = new Rectangle(rect1);
// Print the values of the instance variables for rect2
System.out.println(""Rectangle 2 Length: "" + rect2.length);
System.out.println(""Rectangle 2 Width: "" + rect2.width);
}
} ",0,WE3RESOURCE,NA,JAVA
,"import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class RedisDistributedLock implements Lock {
private final JedisPool jedisPool;
private final String lockKey;
private final String lockValue;
private final long leaseTimeMillis;
private final long waitTimeMillis;
private final ScheduledExecutorService renewalExecutor;
private final ThreadLocal<Boolean> locked = ThreadLocal.withInitial(() -> false);
private final ThreadLocal<Integer> lockCount = ThreadLocal.withInitial(() -> 0);
private final ConcurrentHashMap<String, LockRenewalTask> renewalTasks;
private final ReentrantLock internalLock = new ReentrantLock();
private final Condition lockReleased = internalLock.newCondition();
public RedisDistributedLock(JedisPool jedisPool, String lockKey,
long leaseTimeMillis, long waitTimeMillis) {
this.jedisPool = jedisPool;
this.lockKey = lockKey;
this.lockValue = UUID.randomUUID().toString();
this.leaseTimeMillis = leaseTimeMillis;
this.waitTimeMillis = waitTimeMillis;
this.renewalExecutor = Executors.newSingleThreadScheduledExecutor();
this.renewalTasks = new ConcurrentHashMap<>();
}
@Override
public void lock() {
try {
if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) {
throw new RuntimeException(""Failed to acquire lock within timeout"");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(""Interrupted while acquiring lock"", e);
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) {
throw new RuntimeException(""Failed to acquire lock within timeout"");
}
}
@Override
public boolean tryLock() {
return tryAcquireLock();
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
long waitUntil = System.currentTimeMillis() + unit.toMillis(time);
while (System.currentTimeMillis() < waitUntil) {
if (tryAcquireLock()) {
return true;
}
synchronized (this) {
long remaining = waitUntil - System.currentTimeMillis();
if (remaining > 0) {
wait(100); // Wait and retry
}
}
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
return false;
}
private boolean tryAcquireLock() {
if (locked.get()) {
// Reentrant lock
lockCount.set(lockCount.get() + 1);
return true;
}
try (Jedis jedis = jedisPool.getResource()) {
SetParams params = SetParams.setParams()
.nx()
.px(leaseTimeMillis);
String result = jedis.set(lockKey, lockValue, params);
if (""OK"".equals(result)) {
locked.set(true);
lockCount.set(1);
startLockRenewal();
return true;
}
}
return false;
}
private void startLockRenewal() {
LockRenewalTask task = new LockRenewalTask(lockKey, lockValue, leaseTimeMillis);
renewalTasks.put(lockValue, task);
// Schedule renewal at half the lease time
renewalExecutor.scheduleAtFixedRate(
task,
leaseTimeMillis / 2,
leaseTimeMillis / 2,
TimeUnit.MILLISECONDS
);
}
@Override
public void unlock() {
if (!locked.get()) {
throw new IllegalMonitorStateException(""Lock not held by current thread"");
}
int count = lockCount.get() - 1;
lockCount.set(count);
if (count == 0) {
locked.set(false);
releaseLock();
}
}
private void releaseLock() {
LockRenewalTask task = renewalTasks.remove(lockValue);
if (task != null) {
task.cancel();
}
try (Jedis jedis = jedisPool.getResource()) {
// Use Lua script for atomic release
String luaScript =
""if redis.call('get', KEYS[1]) == ARGV[1] then "" +
"" return redis.call('del', KEYS[1]) "" +
""else "" +
"" return 0 "" +
""end"";
jedis.eval(luaScript, 1, lockKey, lockValue);
}
internalLock.lock();
try {
lockReleased.signalAll();
} finally {
internalLock.unlock();
}
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException(""Conditions not supported"");
}
private static class LockRenewalTask implements Runnable {
private final String lockKey;
private final String lockValue;
private final long leaseTimeMillis;
private volatile boolean cancelled;
LockRenewalTask(String lockKey, String lockValue, long leaseTimeMillis) {
this.lockKey = lockKey;
this.lockValue = lockValue;
this.leaseTimeMillis = leaseTimeMillis;
this.cancelled = false;
}
@Override
public void run() {
if (cancelled) {
return;
}
try (Jedis jedis = new Jedis(""localhost"")) {
String luaScript =
""if redis.call('get', KEYS[1]) == ARGV[1] then "" +
"" return redis.call('pexpire', KEYS[1], ARGV[2]) "" +
""else "" +
"" return 0 "" +
""end"";
Long result = (Long) jedis.eval(
luaScript, 1, lockKey, lockValue,
String.valueOf(leaseTimeMillis)
);
if (result == 0) {
// Lock was released or stolen
cancel();
}
} catch (Exception e) {
// Log error but don't throw
System.err.println(""Failed to renew lock: "" + e.getMessage());
}
}
void cancel() {
this.cancelled = true;
}
}
public void shutdown() {
renewalExecutor.shutdown();
try {
if (!renewalExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
renewalExecutor.shutdownNow();
}
} catch (InterruptedException e) {
renewalExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
}
}",1,DEEPSEEK,Create a distributed lock using Redis with lease time and automatic renewal.,JAVA
,"// Define the Account class
public class Account {
// Private instance variables
private String accountNumber;
private double balance;
// Parameterized constructor with validation
public Account(String accountNumber, double balance) {
// Validate accountNumber
if (accountNumber == null || accountNumber.isEmpty()) {
// Print error message if accountNumber is null or empty
System.err.println(""Error: Account number cannot be null or empty."");
return;
}
// Validate balance
if (balance < 0) {
// Print error message if balance is negative
System.err.println(""Error: Balance cannot be negative."");
return;
}
// Initialize accountNumber with the provided parameter
this.accountNumber = accountNumber;
// Initialize balance with the provided parameter
this.balance = balance;
}
// Main method to test the Account class
public static void main(String[] args) {
// Test with valid data
Account account1 = new Account(""12340009"", 1000.00);
System.out.println(""Account 1 Number: "" + account1.accountNumber);
System.out.println(""Account 1 Balance: "" + account1.balance);
// Test with invalid accountNumber
Account account2 = new Account("""", 400.00);
// Test with invalid balance
Account account3 = new Account(""1230000873"", -200.00);
}
} ",0,WE3RESOURCE,NA,JAVA
,"import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class ApiRateLimiter {
private final Map<String, RateLimiter> limiters;
private final RateLimitConfig config;
public ApiRateLimiter(RateLimitConfig config) {
this.limiters = new ConcurrentHashMap<>();
this.config = config;
}
public boolean allowRequest(String clientId, String endpoint) {
String key = clientId + "":"" + endpoint;
RateLimiter limiter = limiters.computeIfAbsent(key,
k -> createRateLimiter(endpoint)
);
return limiter.tryAcquire();
}
private Rate",1,DEEPSEEK,Create an API gateway rate limiter with multiple rate limiting strategies.,JAVA
,"// Define the Car class
public class Car {
// Private instance variables
private String make;
private String model;
private int year;
// Parameterized constructor with default values
public Car(String make, String model, int year) {
// Initialize make with the provided parameter or a default value
this.make = (make == null || make.isEmpty()) ? ""Unknown Make"" : make;
// Initialize model with the provided parameter or a default value
this.model = (model == null || model.isEmpty()) ? ""Unknown Model"" : model;
// Initialize year with the provided parameter or a default value
this.year = (year <= 0) ? 2000 : year;
}
// Main method to test the Car class
public static void main(String[] args) {
// Create a new Car object with valid data
Car car1 = new Car(""Toyota"", ""Corolla"", 2021);
// Print the values of the instance variables for car1
System.out.println(""Car 1 Make: "" + car1.make);
System.out.println(""Car 1 Model: "" + car1.model);
System.out.println(""Car 1 Year: "" + car1.year);
// Create a new Car object with some invalid data
Car car2 = new Car("""", """", -1);
// Print the values of the instance variables for car2
System.out.println(""Car 2 Make: "" + car2.make);
System.out.println(""Car 2 Model: "" + car2.model);
System.out.println(""Car 2 Year: "" + car2.year);
}
} ",0,WERESOURCE,NA,JAVA
,"static String reverseWords(String s){
String[] w=s.trim().split(""\\s+"");
StringBuilder b=new StringBuilder();
for(int i=w.length-1;i>=0;i--) b.append(w[i]).append("" "");
return b.toString().trim();
} ",1,GPT,"Given a sentence, reverse the order of words without reversing characters.",JAVA
,"// Define the Point class
public class Point {
// Private instance variables
private int x;
private int y;
// Constructor that takes int parameters
public Point(int x, int y) {
// Initialize instance variables
this.x = x;
this.y = y;
}
// Constructor that takes double parameters
public Point(double x, double y) {
// Initialize instance variables by casting double to int
this.x = (int) x;
this.y = (int) y;
}
// Method to print the values of x and y
public void printPoint() {
System.out.println(""Point (x, y): ("" + x + "", "" + y + "")"");
}
// Main method to test the Point class
public static void main(String[] args) {
// Create a Point object using the int constructor
Point point1 = new Point(4, 5);
// Print the values of point1
point1.printPoint();
// Create a Point object using the double constructor
Point point2 = new Point(4.5, 5.5);
// Print the values of point2
point2.printPoint();
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int subarraySum(int[] a,int k){
Map<Integer,Integer> m=new HashMap<>();
m.put(0,1); int sum=0,res=0;
for(int x:a){
sum+=x;
res+=m.getOrDefault(sum-k,0);
m.put(sum,m.getOrDefault(sum,0)+1);
}
return res;
} ",1,GPT,"Given an integer array nums and integer k, return the number of continuous subarrays whose sum equals k.",JAVA
,"// Define the Classroom class
public class Classroom {
// Private instance variables
private String className;
private String[] students;
// Parameterized constructor that initializes className and students
public Classroom(String className, String[] students) {
// Initialize instance variables with provided parameters
this.className = className;
this.students = students;
}
// Method to print the values of className and students
public void printClassroom() {
System.out.println(""Class Name: "" + className);
System.out.print(""Students: "");
for (String student : students) {
System.out.print(student + "" "");
}
System.out.println();
}
// Main method to test the Classroom class
public static void main(String[] args) {
// Create an array of student names
String[] studentArray = {""Andrine"", ""Ruslan"", ""Martin""};
// Create a Classroom object using the parameterized constructor
Classroom classroom = new Classroom(""Science 101"", studentArray);
// Print the values of the instance variables
classroom.printClassroom();
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int longestSeq(int[] a){
Set<Integer> s=new HashSet<>();
for(int x:a) s.add(x);
int best=0;
for(int x:s)
if(!s.contains(x-1)){
int y=x;
while(s.contains(y)) y++;
best=Math.max(best,y-x);
}
return best;
} ",1,GPT,Find the length of the longest sequence of consecutive integers in an unsorted array,JAVA
,"// Define the Singleton class
public class Singleton {
// Private static variable to hold the single instance
private static Singleton singleInstance = null;
// Private constructor to prevent instantiation
private Singleton() {
// Print a message indicating the creation of the instance
System.out.println(""Singleton instance created."");
}
// Public static method to get the single instance of the class
public static Singleton getInstance() {
// If the single instance is null, create a new instance
if (singleInstance == null) {
singleInstance = new Singleton();
}
// Return the single instance
return singleInstance;
}
// Main method to test the Singleton class
public static void main(String[] args) {
// Get the single instance of Singleton
Singleton instance1 = Singleton.getInstance();
// Try to get another instance of Singleton
Singleton instance2 = Singleton.getInstance();
// Check if both instances are the same
if (instance1 == instance2) {
System.out.println(""Both instances are the same."");
} else {
System.out.println(""Instances are different."");
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int[] prod(int[] a){
int n=a.length; int[] r=new int[n];
r[0]=1;
for(int i=1;i<n;i++) r[i]=r[i-1]*a[i-1];
int p=1;
for(int i=n-1;i>=0;i--){ r[i]*=p; p*=a[i]; }
return r;
} ",1,GPT,Return an array where each element is product of all other elements without using division.,JAVA
,"//IncrementThread.java
public class IncrementThread extends Thread {
private Counter counter;
private int incrementsPerThread;
public IncrementThread(Counter counter, int incrementsPerThread) {
this.counter = counter;
this.incrementsPerThread = incrementsPerThread;
}
@Override
public void run() {
for (int i = 0; i < incrementsPerThread; i++) {
counter.increment();
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static List<Integer> anagrams(String s,String p){
int[] c=new int[26];
for(char x:p.toCharArray()) c[x-'a']++;
int l=0,r=0,cnt=p.length();
List<Integer> res=new ArrayList<>();
while(r<s.length()){
if(c[s.charAt(r++)-'a']-- >0) cnt--;
if(cnt==0) res.add(l);
if(r-l==p.length() && c[s.charAt(l++)-'a']++ >=0) cnt++;
}
return res;
} ",1,GPT,Find all start indices of p's anagrams in s.,JAVA
,"// ProducerConsumer.java
import java.util.LinkedList;
import java.util.Queue;
public class ProducerConsumer {
private static final int BUFFER_SIZE = 5;
private static final Queue < Integer > buffer = new LinkedList < > ();
public static void main(String[] args) {
Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());
producerThread.start();
consumerThread.start();
}
static class Producer implements Runnable {
public void run() {
int value = 0;
while (true) {
synchronized(buffer) {
// Wait if the buffer is full
while (buffer.size() == BUFFER_SIZE) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(""Producer produced: "" + value);
buffer.add(value++);
// Notify the consumer that an item is produced
buffer.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Consumer implements Runnable {
public void run() {
while (true) {
synchronized(buffer) {
// Wait if the buffer is empty
while (buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int value = buffer.poll();
System.out.println(""Consumer consumed: "" + value);
// Notify the producer that an item is consumed
buffer.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int[][] kClose(int[][] p,int k){
PriorityQueue<int[]> q=new PriorityQueue<>(
(a,b)->b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1]);
for(int[] x:p){ q.add(x); if(q.size()>k) q.poll(); }
return q.toArray(new int[k][2]);
} ",1,GPT,"WRITE A JAVA PROGRAM WHERE THE Given points in 2D, return k closest points to origin.",JAVA
,"// SharedResourceExercise.java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SharedResourceExercise {
private static final int NUM_THREADS = 3;
private static final int NUM_ITERATIONS = 5;
public static void main(String[] args) {
Lock lock = new ReentrantLock();
SharedResource sharedResource = new SharedResource();
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(new Worker(lock, sharedResource));
threads[i].start();
}
try {
for (Thread thread: threads) {
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Worker implements Runnable {
private Lock lock;
private SharedResource sharedResource;
public Worker(Lock lock, SharedResource sharedResource) {
this.lock = lock;
this.sharedResource = sharedResource;
}
public void run() {
for (int i = 0; i < NUM_ITERATIONS; i++) {
lock.lock();
try {
sharedResource.doWork();
} finally {
lock.unlock();
}
}
}
}
static class SharedResource {
public void doWork() {
String threadName = Thread.currentThread().getName();
System.out.println(""Thread-> "" + threadName + "" is performing work."");
// Perform work on the shared resource
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static String decode(String s){
Stack<Integer> n=new Stack<>();
Stack<String> st=new Stack<>();
String cur=""""; int k=0;
for(char c:s.toCharArray()){
if(Character.isDigit(c)) k=k*10+c-'0';
else if(c=='['){ n.push(k); st.push(cur); k=0; cur=""""; }
else if(c==']'){ cur=st.pop()+cur.repeat(n.pop()); }
else cur+=c;
}
return cur;
} ",1,GPT,"write a java program toDecode strings like ""3[a2[c]]""""accaccacc"".",JAVA
,"//SemaphoreExercise.java
import java.util.concurrent.Semaphore;
public class SemaphoreExercise {
private static final int NUM_THREADS = 5;
private static final int NUM_PERMITS = 2;
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(NUM_PERMITS);
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(new Worker(semaphore));
threads[i].start();
}
try {
for (Thread thread: threads) {
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Worker implements Runnable {
private Semaphore semaphore;
public Worker(Semaphore semaphore) {
this.semaphore = semaphore;
}
public void run() {
try {
semaphore.acquire();
// Perform work that requires the semaphore
System.out.println(""Thread "" + Thread.currentThread().getName() + "" acquired the semaphore."");
Thread.sleep(2000); // Simulating work
System.out.println(""Thread "" + Thread.currentThread().getName() + "" released the semaphore."");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static boolean canFinish(int n,int[][] p){
List<Integer>[] g=new ArrayList[n];
for(int i=0;i<n;i++) g[i]=new ArrayList<>();
int[] in=new int[n];
for(int[] e:p){ g[e[1]].add(e[0]); in[e[0]]++; }
Queue<Integer> q=new LinkedList<>();
for(int i=0;i<n;i++) if(in[i]==0) q.add(i);
int c=0;
while(!q.isEmpty()){
int x=q.poll(); c++;
for(int y:g[x]) if(--in[y]==0) q.add(y);
}
return c==n;
} ",1,GPT,"Given prerequisites, determine if all courses can be finished. WRITE A CYCLE DETECTION GRAPH BASED JAVA PROGRAM FOR THIS CONDITION.",JAVA
,"import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExercise {
private static final int NUM_THREADS = 3;
private static final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS, new BarrierAction());
public static void main(String[] args) {
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(new Worker());
threads[i].start();
}
try {
for (Thread thread: threads) {
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Worker implements Runnable {
public void run() {
try {
System.out.println(""Thread "" + Thread.currentThread().getName() + "" is waiting at the barrier."");
barrier.await();
// Perform work after reaching the barrier
System.out.println(""Thread "" + Thread.currentThread().getName() + "" has crossed the barrier and continued execution."");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
static class BarrierAction implements Runnable {
public void run() {
System.out.println(""Barrier reached! All threads have arrived at the barrier."");
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static void ser(Node r,StringBuilder b){
if(r==null){b.append(""#,"");return;}
b.append(r.val).append("","");
ser(r.left,b); ser(r.right,b);
}
static Node des(Queue<String> q){
String s=q.poll();
if(s.equals(""#"")) return null;
Node n=new Node(Integer.parseInt(s));
n.left=des(q); n.right=des(q);
return n;
} ",1,GPT,Convert binary tree to string and restore it.,JAVA
,"import java.util.concurrent.CountDownLatch;
public class CountDownLatchExercise {
private static final int NUM_THREADS = 3;
private static final CountDownLatch startLatch = new CountDownLatch(1);
private static final CountDownLatch finishLatch = new CountDownLatch(NUM_THREADS);
public static void main(String[] args) {
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(new Worker());
threads[i].start();
}
// Allow threads to start simultaneously
startLatch.countDown();
try {
finishLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(""All threads have finished their work."");
}
static class Worker implements Runnable {
public void run() {
try {
startLatch.await();
// Perform work
System.out.println(""Thread "" + Thread.currentThread().getName() + "" has finished its work."");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
finishLatch.countDown();
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static String minWin(String s,String t){
int[] c=new int[128]; for(char x:t.toCharArray()) c[x]++;
int l=0,start=0,min=Integer.MAX_VALUE,need=t.length();
for(int r=0;r<s.length();r++){
if(c[s.charAt(r)]-- >0) need--;
while(need==0){
if(r-l+1<min){min=r-l+1;start=l;}
if(c[s.charAt(l++)]++==0) need++;
}
}
return min==Integer.MAX_VALUE?"""":s.substring(start,start+min);
} ",1,GPT,write a java program to Find smallest substring in s containing all chars of t.,JAVA
,"import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockExercise {
private static final int NUM_READERS = 3;
private static final int NUM_WRITERS = 2;
public static void main(String[] args) {
ReadWriteLock lock = new ReentrantReadWriteLock();
SharedResource sharedResource = new SharedResource();
// Create and start the reader threads
for (int i = 0; i < NUM_READERS; i++) {
Thread readerThread = new Thread(new Reader(lock, sharedResource));
readerThread.start();
}
// Create and start the writer threads
for (int i = 0; i < NUM_WRITERS; i++) {
Thread writerThread = new Thread(new Writer(lock, sharedResource));
writerThread.start();
}
}
static class Reader implements Runnable {
private ReadWriteLock lock;
private SharedResource sharedResource;
public Reader(ReadWriteLock lock, SharedResource sharedResource) {
this.lock = lock;
this.sharedResource = sharedResource;
}
public void run() {
while (true) {
lock.readLock().lock();
// Read from the shared resource
System.out.println(""Reader "" + Thread.currentThread().getName() + "" reads: "" + sharedResource.read());
lock.readLock().unlock();
// Delay between consecutive reads
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Writer implements Runnable {
private ReadWriteLock lock;
private SharedResource sharedResource;
private int counter = 0;
public Writer(ReadWriteLock lock, SharedResource sharedResource) {
this.lock = lock;
this.sharedResource = sharedResource;
}
public void run() {
while (true) {
lock.writeLock().lock();
// Write to the shared resource
sharedResource.write(""Writer "" + Thread.currentThread().getName() + "" writes: "" + counter++);
lock.writeLock().unlock();
// Delay between consecutive writes
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class SharedResource {
private String data;
public String read() {
return data;
}
public void write(String data) {
this.data = data;
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int ladder(String b,String e,List<String> w){
Set<String> s=new HashSet<>(w); Queue<String> q=new LinkedList<>();
q.add(b); int lvl=1;
while(!q.isEmpty()){
for(int i=q.size();i>0;i--){
String x=q.poll();
if(x.equals(e)) return lvl;
for(int j=0;j<x.length();j++)
for(char c='a';c<='z';c++){
char[] a=x.toCharArray(); a[j]=c;
String y=new String(a);
if(s.remove(y)) q.add(y);
}
} lvl++;
} return 0;
} ",1,GPT,write a java program to Transform begin word to end word by changing one letter at a time.,JAVA
,"import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExercise {
public static void main(String[] args) {
ConcurrentHashMap < String, Integer > map = new ConcurrentHashMap < > ();
// Create and start the writer threads
Thread writerThread1 = new Thread(new Writer(map, ""Thread-1"", 1));
Thread writerThread2 = new Thread(new Writer(map, ""Thread-2"", 2));
writerThread1.start();
writerThread2.start();
// Create and start the reader threads
Thread readerThread1 = new Thread(new Reader(map, ""Thread-1""));
Thread readerThread2 = new Thread(new Reader(map, ""Thread-2""));
readerThread1.start();
readerThread2.start();
}
static class Writer implements Runnable {
private ConcurrentHashMap < String, Integer > map;
private String threadName;
private int value;
public Writer(ConcurrentHashMap < String, Integer > map, String threadName, int value) {
this.map = map;
this.threadName = threadName;
this.value = value;
}
public void run() {
for (int i = 0; i < 5; i++) {
map.put(threadName, value);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Reader implements Runnable {
private ConcurrentHashMap < String, Integer > map;
private String threadName;
public Reader(ConcurrentHashMap < String, Integer > map, String threadName) {
this.map = map;
this.threadName = threadName;
}
public void run() {
for (int i = 0; i < 5; i++) {
Integer value = map.get(threadName);
System.out.println(""Thread "" + threadName + "" read value: "" + value);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int maxRect(int[] h){
Stack<Integer> s=new Stack<>(); int max=0;
for(int i=0;i<=h.length;i++){
int cur=i==h.length?0:h[i];
while(!s.isEmpty()&&cur<h[s.peek()]){
int ht=h[s.pop()];
int w=s.isEmpty()?i:i-s.peek()-1;
max=Math.max(max,ht*w);
} s.push(i);
} return max;
} ",1,GPT,write a program to Find largest rectangle area in histogram.,JAVA
,"import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentQueueExercise {
public static void main(String[] args) {
ConcurrentLinkedQueue < String > queue = new ConcurrentLinkedQueue < > ();
// Create and start the producer threads
Thread producerThread1 = new Thread(new Producer(queue, ""Producer-1""));
Thread producerThread2 = new Thread(new Producer(queue, ""Producer-2""));
producerThread1.start();
producerThread2.start();
// Create and start the consumer threads
Thread consumerThread1 = new Thread(new Consumer(queue, ""Consumer-1""));
Thread consumerThread2 = new Thread(new Consumer(queue, ""Consumer-2""));
consumerThread1.start();
consumerThread2.start();
}
static class Producer implements Runnable {
private ConcurrentLinkedQueue < String > queue;
private String producerName;
private int counter;
public Producer(ConcurrentLinkedQueue < String > queue, String producerName) {
this.queue = queue;
this.producerName = producerName;
this.counter = 0;
}
public void run() {
while (true) {
String item = producerName + ""-Item-"" + counter++;
queue.offer(item);
System.out.println(""Produced: "" + item);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable {
private ConcurrentLinkedQueue < String > queue;
private String consumerName;
public Consumer(ConcurrentLinkedQueue < String > queue, String consumerName) {
this.queue = queue;
this.consumerName = consumerName;
}
public void run() {
while (true) {
String item = queue.poll();
if (item != null) {
System.out.println(consumerName + "" consumed: "" + item);
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int max=Integer.MIN_VALUE;
static int path(Node n){
if(n==null) return 0;
int l=Math.max(0,path(n.left)), r=Math.max(0,path(n.right));
max=Math.max(max,l+r+n.val);
return Math.max(l,r)+n.val;
} ",1,GPT,write a java program to Find max sum of any path in tree.,JAVA
,"import java.util.concurrent.Phaser;
public class PhaserExercise {
public static void main(String[] args) {
// Create a Phaser with 4 registered parties
Phaser phaser = new Phaser(4);
// Create and start three worker threads
Thread thread1 = new Thread(new Worker(phaser, ""Thread 1""));
Thread thread2 = new Thread(new Worker(phaser, ""Thread 2""));
Thread thread3 = new Thread(new Worker(phaser, ""Thread 3""));
Thread thread4 = new Thread(new Worker(phaser, ""Thread 4""));
thread1.start();
thread2.start();
thread3.start();
thread4.start();
// Wait for all threads to complete
phaser.awaitAdvance(phaser.getPhase());
System.out.println(""All threads have completed their tasks."");
}
static class Worker implements Runnable {
private final Phaser phaser;
private final String name;
public Worker(Phaser phaser, String name) {
this.phaser = phaser;
this.name = name;
}
@Override
public void run() {
System.out.println(name + "" starting phase 1"");
phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point
// Perform phase 1 tasks
System.out.println(name + "" performing phase 1 tasks"");
// Wait for all threads to complete phase 1
phaser.arriveAndAwaitAdvance();
System.out.println(name + "" starting phase 2"");
phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point
// Perform phase 2 tasks
System.out.println(name + "" performing phase 2 tasks"");
// Wait for all threads to complete phase 2
phaser.arriveAndAwaitAdvance();
System.out.println(name + "" completed all phases"");
phaser.arriveAndDeregister(); // Deregister from the Phaser
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static String alien(String[] w){
Map<Character,Set<Character>> g=new HashMap<>();
Map<Character,Integer> in=new HashMap<>();
for(String s:w) for(char c:s.toCharArray()){g.putIfAbsent(c,new HashSet<>());in.putIfAbsent(c,0);}
for(int i=0;i<w.length-1;i++)
for(int j=0;j<Math.min(w[i].length(),w[i+1].length());j++)
if(w[i].charAt(j)!=w[i+1].charAt(j)){
if(g.get(w[i].charAt(j)).add(w[i+1].charAt(j)))
in.put(w[i+1].charAt(j),in.get(w[i+1].charAt(j))+1);
break;
}
Queue<Character> q=new LinkedList<>();
for(char c:in.keySet()) if(in.get(c)==0) q.add(c);
StringBuilder r=new StringBuilder();
while(!q.isEmpty()){
char c=q.poll(); r.append(c);
for(char n:g.get(c)) if(in.put(n,in.get(n)-1)==1) q.add(n);
}
return r.toString();
} ",1,GPT,give me an java code to Find character order from sorted alien words.,JAVA
,"import java.util.concurrent.Exchanger;
public class ExchangerExercise {
public static void main(String[] args) {
Exchanger < String > exchanger = new Exchanger < > ();
// Create and start two worker threads
Thread thread1 = new Thread(new Worker(exchanger, ""Data from Thread 1""));
Thread thread2 = new Thread(new Worker(exchanger, ""Data from Thread 2""));
thread1.start();
thread2.start();
}
static class Worker implements Runnable {
private final Exchanger < String > exchanger;
private final String data;
public Worker(Exchanger < String > exchanger, String data) {
this.exchanger = exchanger;
this.data = data;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "" sending data: "" + data);
String receivedData = exchanger.exchange(data); // Exchange data with the other thread
System.out.println(Thread.currentThread().getName() + "" received data: "" + receivedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static boolean dfs(char[][] b,int i,int j,String w,int k){
if(k==w.length()) return true;
if(i<0||j<0||i==b.length||j==b[0].length||b[i][j]!=w.charAt(k)) return false;
char t=b[i][j]; b[i][j]='#';
boolean r=dfs(b,i+1,j,w,k+1)||dfs(b,i-1,j,w,k+1)||dfs(b,i,j+1,w,k+1)||dfs(b,i,j-1,w,k+1);
b[i][j]=t; return r;
} ",1,GPT,give me an efficient java code to Find if word exists in grid using DFS + Trie.,JAVA
,"import java.util.concurrent.*;
public class CallableFutureExercise {
public static void main(String[] args) {
// Create a thread pool with a single worker thread
ExecutorService executor = Executors.newSingleThreadExecutor();
// Submit a Callable task to the executor
Future < String > future = executor.submit(new Task());
// Perform other operations while the task is executing
try {
// Wait for the task to complete and get the result
String result = future.get();
System.out.println(""Task result: "" + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// Shutdown the executor
executor.shutdown();
}
static class Task implements Callable < String > {
@Override
public String call() throws Exception {
// Perform the task and return the result
Thread.sleep(2000); // Simulate some time-consuming operation
return ""Task completed!"";
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int[] redundant(int[][] e){
int[] p=new int[1001];
for(int i=1;i<p.length;i++) p[i]=i;
for(int[] x:e){
int a=f(p,x[0]),b=f(p,x[1]);
if(a==b) return x;
p[a]=b;
} return null;
}
static int f(int[] p,int x){ return p[x]==x?x:(p[x]=f(p,p[x])); } ",1,GPT,write a java code to Find extra edge forming cycle.,JAVA
,"import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorExercise {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// Schedule a task to run after a delay of 2 seconds
executor.schedule(new Task(), 2, TimeUnit.SECONDS);
// Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds
executor.scheduleAtFixedRate(new Task(), 3, 5, TimeUnit.SECONDS);
// Wait for scheduled tasks to complete
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Shutdown the executor
executor.shutdown();
}
static class Task implements Runnable {
@Override
public void run() {
System.out.println(""Task executed at: "" + new Date());
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static boolean match(String s,String p){
boolean[][] d=new boolean[s.length()+1][p.length()+1];
d[0][0]=true;
for(int j=2;j<=p.length();j++)
if(p.charAt(j-1)=='*') d[0][j]=d[0][j-2];
for(int i=1;i<=s.length();i++)
for(int j=1;j<=p.length();j++)
if(p.charAt(j-1)=='*')
d[i][j]=d[i][j-2]||(d[i-1][j]&&(p.charAt(j-2)=='.'||p.charAt(j-2)==s.charAt(i-1)));
else
d[i][j]=d[i-1][j-1]&&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1));
return d[s.length()][p.length()];
}
",1,GPT,write a java program to Implement regex matcher with . and *. ,JAVA
,"import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ForkJoinPoolExercise {
public static void main(String[] args) {
int[] array = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
};
ForkJoinPool forkJoinPool = new ForkJoinPool();
int sum = forkJoinPool.invoke(new SumTask(array, 0, array.length));
System.out.println(""Sum: "" + sum);
}
static class SumTask extends RecursiveTask < Integer > {
private final int[] array;
private final int start;
private final int end;
public SumTask(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if (end - start <= 2) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
} else {
int mid = start + (end - start) / 2;
SumTask leftTask = new SumTask(array, start, mid);
SumTask rightTask = new SumTask(array, mid, end);
invokeAll(leftTask, rightTask);
return leftTask.join() + rightTask.join();
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int decodeWays(String s){
if(s.charAt(0)=='0') return 0;
int a=1,b=1;
for(int i=1;i<s.length();i++){
int c=0;
if(s.charAt(i)!='0') c=b;
int x=Integer.parseInt(s.substring(i-1,i+1));
if(x>=10&&x<=26) c+=a;
a=b; b=c;
} return b;
} ",1,GPT,"You are given a string s containing only digits ('0''9') that represents an encoded message where:
'A'""1""
'B'""2""
...
'Z'""26""
Write a java function to determine how many different ways the string can be decoded into letters.",JAVA
,"import java.util.concurrent.locks.StampedLock;
public class StampedLockExercise {
public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
// Start multiple reader threads
for (int i = 0; i < 5; i++) {
new Thread(() -> {
int value = sharedResource.getValue();
System.out.println(""Reader thread: "" + Thread.currentThread().getName() + "", value: "" + value);
}).start();
}
// Start a writer thread
new Thread(() -> {
sharedResource.setValue(42);
System.out.println(""Writer thread: "" + Thread.currentThread().getName() + "" set value to 42"");
}).start();
}
static class SharedResource {
private int value;
private final StampedLock lock = new StampedLock();
public int getValue() {
long stamp = lock.tryOptimisticRead(); // Optimistically acquire a read lock
int currentValue = value;
if (!lock.validate(stamp)) { // Check for concurrent write
stamp = lock.readLock(); // Upgrade to a read lock
try {
currentValue = value;
} finally {
lock.unlockRead(stamp); // Release the read lock
}
}
return currentValue;
}
public void setValue(int value) {
long stamp = lock.writeLock(); // Acquire a write lock
try {
this.value = value;
} finally {
lock.unlockWrite(stamp); // Release the write lock
}
}
}
} ",0,WE3RESOURCE,NA,JAVA
,"static int dfs(int[][] m,int i,int j,int[][] d){
if(d[i][j]>0) return d[i][j];
int r=1;
for(int[] x:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}){
int a=i+x[0],b=j+x[1];
if(a>=0&&b>=0&&a<m.length&&b<m[0].length&&m[a][b]>m[i][j])
r=Math.max(r,1+dfs(m,a,b,d));
}
return d[i][j]=r;
} ",1,GPT,"You are given an m x n integer matrix matrix.
From any cell, you can move up, down, left, or right to another cell only if the next cell has a strictly larger value.
Write a java function that returns the length of the longest strictly increasing path in the matrix.",JAVA
,"public int romanToInt(String s) {
int ans = 0, num = 0;
for (int i = s.length()-1; i >= 0; i--) {
switch(s.charAt(i)) {
case 'I': num = 1; break;
case 'V': num = 5; break;
case 'X': num = 10; break;
case 'L': num = 50; break;
case 'C': num = 100; break;
case 'D': num = 500; break;
case 'M': num = 1000; break;
}
if (4 * num < ans) ans -= num;
else ans += num;
}
return ans;
}",0,leetcode,NA,JAVA
,"// 1. Binary Search (AI-generated for sorted array lookup)
public class BinarySearch {
public static int search(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
}
",1,PERPLEXITY,Write a Java method for binary search on a sorted integer array that returns the index or -1 if not found,JAVA
,"class Solution {
public String intToRoman(int num) {
String Roman = """";
int[][] storeIntRoman = {{1000, ""M""}, {900, ""CM""}, {500, ""D""}, {400, ""CD""}, {100, ""C""}, {90, ""XC""}, {50, ""L""}, {40, ""XL""}, {10, ""X""}, {9, ""IX""}, {5, ""V""}, {4, ""IV""}, {1, ""I""}};
for (int i = 0; i < storeIntRoman.length; i++) {
while (num >= storeIntRoman[i][0]) {
Roman += storeIntRoman[i][1];
num -= storeIntRoman[i][0];
}
}
return Roman;
}
}",0,leetcode,NA,JAVA
,"public class BubbleSort {
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
",1,PERPLEXITY,Create a Java class with a static method to sort an integer array using bubble sort in-place.,JAVA
,"class Solution {
private Map<Character, String> digitToLetters = new HashMap<>();
private List<String> resultList = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return resultList;
}
digitToLetters.put('2', ""abc"");
digitToLetters.put('3', ""def"");
digitToLetters.put('4', ""ghi"");
digitToLetters.put('5', ""jkl"");
digitToLetters.put('6', ""mno"");
digitToLetters.put('7', ""pqrs"");
digitToLetters.put('8', ""tuv"");
digitToLetters.put('9', ""wxyz"");
generateCombinations(digits, 0, new StringBuilder());
return resultList;
}
private void generateCombinations(String digits, int currentIndex, StringBuilder currentCombination) {
if (currentIndex == digits.length()) {
resultList.add(currentCombination.toString());
return;
}
char currentDigit = digits.charAt(currentIndex);
String letterOptions = digitToLetters.get(currentDigit);
if (letterOptions != null) {
for (int i = 0; i < letterOptions.length(); i++) {
char letter = letterOptions.charAt(i);
currentCombination.append(letter);
generateCombinations(digits, currentIndex + 1, currentCombination);
currentCombination.deleteCharAt(currentCombination.length() - 1);
}
}
}
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[][] rows = new boolean[9][9];
boolean[][] cols = new boolean[9][9];
boolean[][] boxes = new boolean[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '1';
int boxIndex = (i / 3) * 3 + (j / 3);
if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
return false;
}
rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true;
}
}
}
return true;
}
}",0,leetcode,NA,JAVA
,"import java.util.HashMap;
public class Fibonacci {
private static HashMap<Integer, Long> memo = new HashMap<>();
public static long fib(int n) {
if (n <= 1) return n;
if (memo.containsKey(n)) return memo.get(n);
long result = fib(n - 1) + fib(n - 2);
memo.put(n, result);
return result;
}
}
",1,PERPLEXITY,Write a Java Fibonacci function using recursion with HashMap memoization for efficiency,JAVA
,"class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0)
return ""0"";
string fraction;
if ((numerator < 0) ^ (denominator < 0))
fraction += ""-"";
long long dividend = llabs((long long)numerator);
long long divisor = llabs((long long)denominator);
fraction += to_string(dividend / divisor);
long long remainder = dividend % divisor;
if (remainder == 0) {
return fraction;
}
fraction += ""."";
unordered_map<long long, int> map;
while (remainder != 0) {
if (map.count(remainder)) {
fraction.insert(map[remainder], ""("");
fraction += "")"";
break;
}
map[remainder] = fraction.size();
remainder *= 10;
fraction += to_string(remainder / divisor);
remainder %= divisor;
}
return fraction;
}
};",0,leetcode,NA,JAVA
,"class Solution {
public int numJewelsInStones(String jewels, String stones)
{
int cnt=0;
for(int i=0;i<stones.length();i++)
{
char ch=stones.charAt(i);
for(int j=0;j<jewels.length();j++)
{
if(jewels.charAt(j)==ch)
{
cnt++;
break;
}
}
}
return cnt;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int maxPoints(int[][] points) {
int n = points.length;
if (n <= 2) return n;
int result = 0;
for (int i = 0; i < n; i++) {
Map<String, Integer> map = new HashMap<>();
int max = 0;
for (int j = i + 1; j < n; j++) {
int dx = points[j][0] - points[i][0];
int dy = points[j][1] - points[i][1];
int g = gcd(dx, dy);
dx /= g;
dy /= g;
String key = dx + "","" + dy;
map.put(key, map.getOrDefault(key, 0) + 1);
max = Math.max(max, map.get(key));
}
result = Math.max(result, max + 1); // +1 for anchor point
}
return result;
}
private int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
}",0,leetcode,NA,JAVA
,"import java.util.ArrayList;
public class Stack<T> {
private ArrayList<T> stack = new ArrayList<>();
public void push(T item) { stack.add(item); }
public T pop() { return stack.remove(stack.size() - 1); }
public T peek() { return stack.get(stack.size() - 1); }
public boolean isEmpty() { return stack.isEmpty(); }
}
",1,PERPLEXITY,"Implement a generic Stack class in Java using ArrayList with push, pop, peek, and isEmpty methods",JAVA
,"public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}",0,leetcode,NA,JAVA
,"class ListNode {
int val; ListNode next;
ListNode(int val) { this.val = val; }
}
public class LinkedListOps {
public ListNode reverse(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr; curr = next;
}
return prev;
}
}
",1,PERPLEXITY,"Write Java code to reverse a singly linked list given a ListNode head, using iterative approach",JAVA
,"public List<String> wordBreak(String s, Set<String> wordDict) {
return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
}
// DFS function returns an array including all substrings derived from s.
List<String> DFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>>map) {
if (map.containsKey(s))
return map.get(s);
LinkedList<String>res = new LinkedList<String>();
if (s.length() == 0) {
res.add("""");
return res;
}
for (String word : wordDict) {
if (s.startsWith(word)) {
List<String>sublist = DFS(s.substring(word.length()), wordDict, map);
for (String sub : sublist)
res.add(word + (sub.isEmpty() ? """" : "" "") + sub);
}
}
map.put(s, res);
return res;
}",0,leetcode,NA,JAVA
,"class TreeNode {
int val; TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class TreeTraversal {
public void inorder(TreeNode root, List<Integer> result) {
if (root == null) return;
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
}
}
",1,PERPLEXITY,"Create a Java method for inorder traversal of a binary tree, collecting values in a List",JAVA
,"public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode iter = head, next;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while (iter != null) {
next = iter.next;
RandomListNode copy = new RandomListNode(iter.label);
iter.next = copy;
copy.next = next;
iter = next;
}
// Second round: assign random pointers for the copy nodes.
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
// Third round: restore the original list, and extract the copy list.
iter = head;
RandomListNode pseudoHead = new RandomListNode(0);
RandomListNode copy, copyIter = pseudoHead;
while (iter != null) {
next = iter.next.next;
// extract the copy
copy = iter.next;
copyIter.next = copy;
copyIter = copy;
// restore the original list
iter.next = next;
iter = next;
}
return pseudoHead.next;
}",0,leetcode,NA,JAVA
,"import java.util.*;
class Solution {
public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
Map<String, Integer> evalmap = new HashMap<>();
for (int i = 0; i < evalvars.length; i++) evalmap.put(evalvars[i], evalints[i]);
List<String> tokens = tokenize(expression);
Map<List<String>, Integer> poly = parseExpression(tokens, evalmap);
List<Map.Entry<List<String>, Integer>> list = new ArrayList<>(poly.entrySet());
list.sort((a, b) -> {
if (b.getKey().size() != a.getKey().size()) return b.getKey().size() - a.getKey().size();
// lexicographic compare by joining with '*'
return String.join(""*"", a.getKey()).compareTo(String.join(""*"", b.getKey()));
});
List<String> ans = new ArrayList<>();
for (var e : list) {
int coeff = e.getValue();
if (coeff == 0) continue;
StringBuilder sb = new StringBuilder();
sb.append(coeff);
for (String v : e.getKey()) sb.append(""*"").append(v);
ans.add(sb.toString());
}
return ans;
}
private List<String> tokenize(String expr) {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (char c : expr.toCharArray()) {
if (Character.isLetterOrDigit(c)) sb.append(c);
else {
if (sb.length() > 0) { tokens.add(sb.toString()); sb.setLength(0); }
if (c == '+' || c == '-' || c == '*' || c == '(' || c == ')') tokens.add(String.valueOf(c));
}
}
if (sb.length() > 0) tokens.add(sb.toString());
return tokens;
}
private Map<List<String>, Integer> parseExpression(List<String> tokens, Map<String, Integer> evalmap) {
Deque<Map<List<String>, Integer>> vals = new ArrayDeque<>();
Deque<String> ops = new ArrayDeque<>();
Map<String, Integer> prec = Map.of(""+"",1, ""-"",1, ""*"",2);
for (String tok : tokens) {
if (tok.equals(""("")) ops.push(tok);
else if (tok.equals("")"")) {
while (!ops.peek().equals(""("")) applyOp(vals, ops.pop());
ops.pop();
} else if (prec.containsKey(tok)) {
while (!ops.isEmpty() && prec.containsKey(ops.peek()) && prec.get(ops.peek()) >= prec.get(tok)) {
applyOp(vals, ops.pop());
}
ops.push(tok);
} else {
vals.push(parseToken(tok, evalmap));
}
}
while (!ops.isEmpty()) applyOp(vals, ops.pop());
return vals.isEmpty() ? new HashMap<>() : vals.pop();
}
private void applyOp(Deque<Map<List<String>, Integer>> vals, String op) {
Map<List<String>, Integer> b = vals.pop();
Map<List<String>, Integer> a = vals.pop();
if (op.equals(""+"")) vals.push(add(a, b));
else if (op.equals(""-"")) vals.push(sub(a, b));
else vals.push(mul(a, b));
}
private Map<List<String>, Integer> parseToken(String tok, Map<String, Integer> evalmap) {
Map<List<String>, Integer> res = new HashMap<>();
if (tok.matches(""-?\\d+"")) {
res.put(Collections.emptyList(), Integer.parseInt(tok));
} else if (evalmap.containsKey(tok)) {
res.put(Collections.emptyList(), evalmap.get(tok));
} else {
res.put(Arrays.asList(tok), 1);
}
return res;
}
private Map<List<String>, Integer> combine(Map<List<String>, Integer> m) {
Map<List<String>, Integer> res = new HashMap<>();
for (var e : m.entrySet()) {
if (e.getValue() != 0) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
}
res.entrySet().removeIf(kv -> kv.getValue() == 0);
return res;
}
private Map<List<String>, Integer> add(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>(a);
for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
return combine(res);
}
private Map<List<String>, Integer> sub(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>(a);
for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) - e.getValue());
return combine(res);
}
private Map<List<String>, Integer> mul(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>();
for (var ea : a.entrySet()) {
for (var eb : b.entrySet()) {
List<String> merged = new ArrayList<>(ea.getKey());
merged.addAll(eb.getKey());
Collections.sort(merged);
res.put(merged, res.getOrDefault(merged, 0) + ea.getValue() * eb.getValue());
}
}
return combine(res);
}
}",0,leetcode,NA,JAVA
,"class Solution {
public Node cloneGraph(Node node) {
if (node == null) return null;
Map<Node, Node> copiedMap = new HashMap<>();
bfs(node, copiedMap);
return copiedMap.get(node);
}
private void bfs(Node startNode, Map<Node, Node> copiedMap) {
Queue<Node> queue = new ArrayDeque<>(); // include nodes that have been visited (copied) only
// check & copy node at Generation
copiedMap.put(startNode, new Node(startNode.val));
queue.offer(startNode);
while (!queue.isEmpty()) {
Node node = queue.poll();
// copy & link, add neighbors to Queue
for (Node neighbor: node.neighbors) {
// check & copy node at Generation
if (copiedMap.containsKey(neighbor)) { // neighbor is already visited (copied), just link
// IMPORTANT: DON'T JUST CONTINUE!
copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
} else { // copy, link, add neighbor to queue to be visited
copiedMap.put(neighbor, new Node(neighbor.val));
queue.offer(neighbor);
copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
}
}
}
}
}",0,leetcode,NA,JAVA
,"class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= nums.length; i++) {
if (!numSet.contains(i)) {
result.add(i);
}
}
return result;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
if(nums.length==0){
return 0;
}
for(int i : nums){
set.add(i);
}
int max = 0;
for(int i : nums){
if(!set.contains(i)){
continue;
}
int n = i;
int m = i;
int length = 1;
while(set.contains(n+1)){
n=(n+1);
set.remove(n);
length++;
}
while(set.contains(m-1)){
m= m-1;
set.remove(m);
length++;
}
max = Math.max(length, max);
}
return max;
}
}",0,leetcode,NA,JAVA
,"public class PalindromeChecker {
public static boolean isPalindrome(String s) {
s = s.toLowerCase().replaceAll(""[^a-z0-9]"", """");
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
}
",1,PERPLEXITY,"Write a Java static method to check if a string is a palindrome, ignoring case and non-alphanumeric chars.",JAVA
,"// Simple BFS approach (can TLE on large inputs)
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
Queue<List<String>> q = new ArrayDeque<>();
Set<String> set = new HashSet<>(wordList);
List<List<String>> ans = new ArrayList<>();
if (!set.contains(endWord)) return ans;
q.add(new ArrayList<>(List.of(beginWord)));
boolean found = false;
while (!q.isEmpty() && !found) {
int size = q.size();
Set<String> used = new HashSet<>();
for (int k = 0; k < size; k++) {
List<String> path = q.poll();
String last = path.get(path.size() - 1);
if (last.equals(endWord)) {
ans.add(path);
found = true;
}
char[] arr = last.toCharArray();
for (int i = 0; i < arr.length; i++) {
char original = arr[i];
for (char c = 'a'; c <= 'z'; c++) {
if (c == original) continue;
arr[i] = c;
String next = new String(arr);
if (set.contains(next)) {
List<String> newPath = new ArrayList<>(path);
newPath.add(next);
q.add(newPath);
used.add(next);
}
}
arr[i] = original;
}
}
for (String w : used) set.remove(w);
}
return ans;
}
}",0,leetcode,NA,JAVA
,"import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateUtil {
public static String format(LocalDate date) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(""yyyy-MM-dd"");
return date.format(fmt);
}
}
",1,PERPLEXITY,Create a Java utility class with a method to format LocalDate as yyyy-MM-dd string,JAVA
,"class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
Deque<Integer> preorderQueue = new ArrayDeque<>();
for (int val : preorder) {
preorderQueue.offer(val);
}
return build(preorderQueue, inorder);
}
private TreeNode build(Deque<Integer> preorder, int[] inorder) {
if (inorder.length > 0) {
int idx = indexOf(inorder, preorder.poll());
TreeNode root = new TreeNode(inorder[idx]);
root.left = build(preorder, Arrays.copyOfRange(inorder, 0, idx));
root.right = build(preorder, Arrays.copyOfRange(inorder, idx + 1, inorder.length));
return root;
}
return null;
}
private int indexOf(int[] arr, int value) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
return i;
}
}
return -1; // shouldn't happen with valid input
}
}",0,leetcode,NA,JAVA
,"class Person {
String name; int age;
Person(String name, int age) { this.name = name; this.age = age; }
}
class Employee extends Person {
String dept; double salary;
Employee(String n, int a, String d, double s) {
super(n, a); dept = d; salary = s;
}
}
",1,PERPLEXITY,"Define Java classes Person and Employee with inheritance, constructor chaining, and fields name, age, dept, salary",JAVA
,"class Solution {
public String minWindow(String s, String t) {
if (s == null || t == null || s.length() == 0 || t.length() == 0 ||
s.length() < t.length()) {
return new String();
}
int left = 0;
int right = 0;
int windowFreqArr[] = new int[256];
int targetFreqArr[] = new int[256];
int startIdx = -1;
int minLength = Integer.MAX_VALUE;
for (int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
targetFreqArr[ch]++;
}
int required = t.length();
for (right = 0; right < s.length(); right++) {
char rightChar = s.charAt(right);
windowFreqArr[rightChar]++;
// If this character is needed (count > 0), decrement required
if (targetFreqArr[rightChar] > 0) {
required--; // One less character needed
}
targetFreqArr[rightChar]--;
// When we have all characters, try to minimize window
while (required == 0) {
int length = right - left + 1;
if (length < minLength) {
minLength = length;
startIdx = left;
}
// increment the left
char leftChar = s.charAt(left);
windowFreqArr[leftChar]--;
left++;
// If a needed character is removed, window becomes invalid
targetFreqArr[leftChar]++;
if (targetFreqArr[leftChar] > 0) {
required++; // We now need this character again
}
}
}
return startIdx == -1 ? """" : s.substring(startIdx, startIdx + minLength);
}
}",0,leetcode,NA,JAVA
,"class Solution {
public String reorganizeString(String s) {
// count ch
Map<Character, Integer> freq = new HashMap<>();
for (char ch : s.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
// sort by cnt
List<Map.Entry<Character, Integer>> list = new ArrayList<>(freq.entrySet());
list.sort((a,b) -> b.getValue() - a.getValue());
// create buckets of str
int maxFreq = list.get(0).getValue();
StringBuilder[] buckets = new StringBuilder[maxFreq];
// iterate over ch and cnts and fill buckets in circular fashion
int k = 0; // bucket ind
for (int i = 0; i < freq.size(); i++) {
for (int j = 0; j < list.get(i).getValue(); j++) {
int id = k % maxFreq;
if (buckets[id] == null) buckets[id] = new StringBuilder();
buckets[id].append(list.get(i).getKey());
k++;
}
}
// merge
StringBuilder res = new StringBuilder();
for (StringBuilder sb : buckets) {
res.append(sb);
}
String resStr = res.toString();
// validate
for (int i = 0; i < resStr.length() - 1; i++) {
if (resStr.charAt(i) == resStr.charAt(i+1)) return """";
}
return resStr;
}
}
// ababb
// bbbb
// cccc - 3
// aaa
// bbb
// ca cb cx c
// abcabccc
// c
// abcdabcdabcdddddddd",0,leetcode,NA,JAVA
,"public class Solution {
public void setZeroes(int[][] matrix) {
boolean fr = false,fc = false;
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == 0) {
if(i == 0) fr = true;
if(j == 0) fc = true;
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1; i < matrix.length; i++) {
for(int j = 1; j < matrix[0].length; j++) {
if(matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}}
}
if(fr) {
for(int j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
if(fc) {
for(int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}} ",0,leetcode,NA,JAVA
,,,leetcode,NA,JAVA
,"public class Solution {
private static final Map<Character, Integer> A = new HashMap<>();
static { A.put('A',0); A.put('C',1); A.put('G',2); A.put('T',3); }
private final int A_SIZE_POW_9 = (int) Math.pow(A.size(), 9);
public List<String> findRepeatedDnaSequences(String s) {
Set<String> res = new HashSet<>();
Set<Integer> hashes = new HashSet<>();
for (int i = 0, rhash = 0; i < s.length(); i++) {
if (i > 9) rhash -= A_SIZE_POW_9 * A.get(s.charAt(i-10));
rhash = A.size() * rhash + A.get(s.charAt(i));
if (i > 8 && !hashes.add(rhash)) res.add(s.substring(i-9,i+1));
}
return new ArrayList<>(res);
}
}",0,leetcode,NA,JAVA
,"public class QuickSort {
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
sort(arr, low, pi - 1);
sort(arr, pi + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
}
}
int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp;
return i + 1;
}
}
",1,PERPLEXITY,Write a Java quicksort algorithm to sort an integer array in-place using the Lomuto partition scheme,JAVA
,"class Trie {
Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
root.insert(word, 0);
}
public boolean search(String word) {
return root.search(word, 0);
}
public boolean startsWith(String prefix) {
return root.startsWith(prefix, 0);
}
class Node {
Node[] nodes;
boolean isEnd;
Node() {
nodes = new Node[26];
}
private void insert(String word, int idx) {
if (idx >= word.length()) return;
int i = word.charAt(idx) - 'a';
if (nodes[i] == null) {
nodes[i] = new Node();
}
if (idx == word.length()-1) nodes[i].isEnd = true;
nodes[i].insert(word, idx+1);
}
private boolean search(String word, int idx) {
if (idx >= word.length()) return false;
Node node = nodes[word.charAt(idx) - 'a'];
if (node == null) return false;
if (idx == word.length() - 1 && node.isEnd) return true;
return node.search(word, idx+1);
}
private boolean startsWith(String prefix, int idx) {
if (idx >= prefix.length()) return false;
Node node = nodes[prefix.charAt(idx) - 'a'];
if (node == null) return false;
if (idx == prefix.length() - 1) return true;
return node.startsWith(prefix, idx+1);
}
}
}",0,leetcode,NA,JAVA
,"class Solution {
public String[] findRestaurant(String[] list1, String[] list2) {
int min = 10000;
ArrayList<String> arr = new ArrayList<>();
for (int i = 0; i < list1.length; i++)
for (int j = 0; j < list2.length; j++)
if (list1[i].equals(list2[j])) {
if (i + j <= min) {
if (i + j < min) {
arr.clear();
min = i + j;
}
arr.add(list1[i]);
}
break;
}
return arr.toArray(new String[0]);
}
}",0,leetcode,NA,JAVA
,"class Solution {
public List<Integer> majorityElement(int[] nums) {
// Create a frequency map to store the count of each element
Map<Integer, Integer> elementCountMap = new HashMap<>();
// Iterate through the input array to count element occurrences
for (int i = 0; i < nums.length; i++) {
elementCountMap.put(nums[i], elementCountMap.getOrDefault(nums[i], 0) + 1);
}
List<Integer> majorityElements = new ArrayList<>();
int threshold = nums.length / 3;
// Iterate through the frequency map to identify majority elements
for (Map.Entry<Integer, Integer> entry : elementCountMap.entrySet()) {
int element = entry.getKey();
int count = entry.getValue();
// Check if the element count is greater than the threshold
if (count > threshold) {
majorityElements.add(element);
}
}
return majorityElements;
}
}",0,leetcode,NA,JAVA
,"public class MergeArrays {
public static int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) result[k++] = a[i++];
else result[k++] = b[j++];
}
while (i < a.length) result[k++] = a[i++];
while (j < b.length) result[k++] = b[j++];
return result;
}
}
",1,PERPLEXITY,Create a Java method that merges two sorted integer arrays into one sorted array without extra space if possible.,JAVA
,"class Solution {
public int nthUglyNumber(int n) {
int[] primes = {2, 3, 5};
PriorityQueue<Long> uglyHeap = new PriorityQueue<>();
HashSet<Long> visited = new HashSet<>();
uglyHeap.add(1L);
visited.add(1L);
long curr = 1L;
for (int i = 0; i < n; i++) {
curr = uglyHeap.poll();
for (int prime : primes) {
long new_ugly = curr * prime;
if (!visited.contains(new_ugly)) {
uglyHeap.add(new_ugly);
visited.add(new_ugly);
}
}
}
return (int)curr;
}
}",0,leetcode,NA,JAVA
,"public class FactorialDP {
public static long factorial(int n) {
if (n <= 1) return 1;
long[] dp = new long[n + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] * i;
}
return dp[n];
}
}
",1,PERPLEXITY,Implement a Java dynamic programming solution to compute factorial of a large number using an array.,JAVA
,"class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int[] v = new int[n+1];
Arrays.fill(v, -1);
for(int i = 0; i < nums.length; i++) {
v[nums[i]] = nums[i];
}
for(int i = 0; i < v.length; i++) {
if(v[i] == -1) return i;
}
return 0;
}
}
",0,leetcode,NA,JAVA
,"public class PrimeChecker {
public static boolean isPrime(long n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (long i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
}
",1,PERPLEXITY,"Write an efficient Java method to check if a number is prime, optimized for large inputs.",JAVA
,"class Solution {
public boolean isIsomorphic(String s, String t) {
HashMap<Character, Integer> charIndexS = new HashMap<>();
HashMap<Character, Integer> charIndexT = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (!charIndexS.containsKey(s.charAt(i))) {
charIndexS.put(s.charAt(i), i);
}
if (!charIndexT.containsKey(t.charAt(i))) {
charIndexT.put(t.charAt(i), i);
}
if (!charIndexS.get(s.charAt(i)).equals(charIndexT.get(t.charAt(i)))) {
return false;
}
}
return true;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public List<Integer> partitionLabels(String s) {
Map<Character, Integer> lastOccurrence = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
lastOccurrence.put(s.charAt(i), i);
}
List<Integer> result = new ArrayList<>();
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
end = Math.max(end, lastOccurrence.get(s.charAt(i)));
if (i == end) {
result.add(end - start + 1);
start = i + 1;
}
}
return result;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split("" "");
if (pattern.length() != words.length) return false;
Map<Character, String> charWord = new HashMap<>();
Map<String, Character> wordChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
String word = words[i];
if (charWord.containsKey(ch)) {
if (!charWord.get(ch).equals(word)) {
return false;
}
} else if (wordChar.containsKey(word)) {
return false;
} else {
charWord.put(ch, word);
wordChar.put(word, ch);
}
}
return true;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public String frequencySort(String s) {
Map<Character, Integer> freqMap = new HashMap<>();
for (char c : s.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
List<Map.Entry<Character, Integer>> list =
new ArrayList<>(freqMap.entrySet());
list.sort((a, b) -> b.getValue() - a.getValue());
StringBuilder sb = new StringBuilder();
for (Map.Entry<Character, Integer> entry : list) {
char ch = entry.getKey();
int count = entry.getValue();
for (int i = 0; i < count; i++) {
sb.append(ch);
}
}
return sb.toString();
}
}
",0,leetcode,NA,JAVA
,"// With comments
class RandomizedCollection {
private Map<Integer, Set<Integer>> map; // Map to store values and their indices in the list
private List<Integer> list; // List to store the values in the order they were inserted
public RandomizedCollection() {
this.map = new HashMap<>();
this.list = new ArrayList<>();
}
// Inserts a value into the collection, returns true if the value was not present before
public boolean insert(int val) {
boolean ans = map.containsKey(val); // Check if the value is already present
map.computeIfAbsent(val, key -> new HashSet<>()).add(list.size()); // Add the index to the set in the map
list.add(val); // Add the value to the list
return !ans; // Return true if the value was not present before
}
// Removes a value from the collection, returns true if the value was present
public boolean remove(int val) {
if (!map.containsKey(val)) return false; // If the value is not present, return false
int indexVal = map.get(val).iterator().next(); // Get one of the indices of the value
map.get(val).remove(indexVal); // Remove the index from the set in the map
if (map.get(val).isEmpty()) map.remove(val); // If the set is empty, remove the value from the map
if (indexVal != list.size() - 1) {
// If the index to be removed is not the last index in the list
// Update the map for the last value in the list
map.get(list.get(list.size() - 1)).remove(list.size() - 1);
map.get(list.get(list.size() - 1)).add(indexVal);
list.set(indexVal, list.get(list.size() - 1)); // Replace the value at indexVal with the last value
}
list.remove(list.size() - 1); // Remove the last element from the list
return true; // Return true since the value was present and removed
}
// Returns a random element from the collection
public int getRandom() {
Random random = new Random();
int ind = random.nextInt(list.size()); // Generate a random index
return list.get(ind); // Return the value at the random index
}
}",0,leetcode,NA,JAVA
,"import java.util.Arrays;
public class AnagramDetector {
public static boolean areAnagrams(String s1, String s2) {
s1 = s1.toLowerCase().replaceAll(""\\s"", """");
s2 = s2.toLowerCase().replaceAll(""\\s"", """");
if (s1.length() != s2.length()) return false;
char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray();
Arrays.sort(a1); Arrays.sort(a2);
return Arrays.equals(a1, a2);
}
}
",1,PERPLEXITY,"Create a Java function to detect if two strings are anagrams, ignoring case and spaces.",JAVA
,"
class RandomizedSet {
private ArrayList<Integer> list;
private Map<Integer, Integer> map;
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
}
public boolean search(int val) {
return map.containsKey(val);
}
public boolean insert(int val) {
if (search(val)) return false;
list.add(val);
map.put(val, list.size() - 1);
return true;
}
public boolean remove(int val) {
if (!search(val)) return false;
int index = map.get(val);
list.set(index, list.get(list.size() - 1));
map.put(list.get(index), index);
list.remove(list.size() - 1);
map.remove(val);
return true;
}
public int getRandom() {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
}
",0,leetcode,NA,JAVA
,"import java.util.LinkedList;
public class Queue<T> {
private LinkedList<T> list = new LinkedList<>();
public void enqueue(T item) { list.addLast(item); }
public T dequeue() { return list.pollFirst(); }
public T peek() { return list.peekFirst(); }
public int size() { return list.size(); }
public boolean isEmpty() { return list.isEmpty(); }
}
",1,PERPLEXITY,"Implement a generic Queue class in Java using LinkedList with enqueue, dequeue, and size methods.",JAVA
,"class Twitter {
private static int timestamp = 0;
private Map<Integer, List<int[]>> tweets = new HashMap<>();
private Map<Integer, Set<Integer>> followMap = new HashMap<>();
public void postTweet(int userId, int tweetId) {
tweets.putIfAbsent(userId, new ArrayList<>());
tweets.get(userId).add(new int[]{timestamp++, tweetId});
}
public List<Integer> getNewsFeed(int userId) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
Set<Integer> followees = followMap.getOrDefault(userId, new HashSet<>());
followees.add(userId);
for (int followee : followees) {
List<int[]> tweetList = tweets.getOrDefault(followee, new ArrayList<>());
maxHeap.addAll(tweetList);
}
List<Integer> res = new ArrayList<>();
while (!maxHeap.isEmpty() && res.size() < 10) {
res.add(maxHeap.poll()[1]);
}
return res;
}
public void follow(int followerId, int followeeId) {
followMap.putIfAbsent(followerId, new HashSet<>());
followMap.get(followerId).add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
if (followMap.containsKey(followerId)) {
followMap.get(followerId).remove(followeeId);
}
}
}",0,leetcode,NA,JAVA
,"public class CustomEntry<K, V> {
private K key;
private V value;
private CustomEntry<K, V> next;
public CustomEntry(K key, V value) {
this.key = key; this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
public void setValue(V value) { this.value = value; }
public CustomEntry<K, V> getNext() { return next; }
public void setNext(CustomEntry<K, V> next) { this.next = next; }
}
",1,PERPLEXITY,Define a custom Entry class for Java HashMap-like structure with key-value pairs.,JAVA
,"class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
int l1 = nums1.length;
int l2 = nums2.length;
int i = 0, j = 0, k = 0;
Arrays.sort(nums1);
Arrays.sort(nums2);
while( i < l1 && j < l2)
{
if(nums1[i] < nums2[j])
{
i++;
}
else if(nums1[i] > nums2[j])
{
j++;
}
else
{
nums1[k++] = nums1[i++];
j++;
}
}
return Arrays.copyOfRange(nums1,0,k);
}
}",0,leetcode,NA,JAVA
,"class TreeNode {
int val; TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class BSTInsert {
public TreeNode insert(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
TreeNode curr = root;
while (true) {
if (val < curr.val) {
if (curr.left == null) { curr.left = new TreeNode(val); break; }
curr = curr.left;
} else {
if (curr.right == null) { curr.right = new TreeNode(val); break; }
curr = curr.right;
}
}
return root;
}
}
",1,PERPLEXITY,Write Java code for inserting a node into a Binary Search Tree iteratively,JAVA
,"public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer>[] bucket = new List[nums.length + 1];
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
for (int n : nums) {
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
}
for (int key : frequencyMap.keySet()) {
int frequency = frequencyMap.get(key);
if (bucket[frequency] == null) {
bucket[frequency] = new ArrayList<>();
}
bucket[frequency].add(key);
}
List<Integer> res = new ArrayList<>();
for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
if (bucket[pos] != null) {
res.addAll(bucket[pos]);
}
}
return res;
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean pyramidTransition(String bottom, List<String> allowed) {
List<Character>[][] map = new List[6][6];
Map<String, Boolean> memo = new HashMap<>();
for (String al : allowed) {
int a = al.charAt(0) - 'A';
int b = al.charAt(1) - 'A';
if (map[a][b] == null) map[a][b] = new ArrayList<>();
map[a][b].add(al.charAt(2));
}
return dfs(bottom.toCharArray(), map, memo);
}
private boolean dfs(char[] row, List<Character>[][] map, Map<String, Boolean> memo) {
int n = row.length;
if (n == 1) return true;
String key = new String(row);
if (memo.containsKey(key)) return memo.get(key);
List<char[]> nextRows = new ArrayList<>();
getNextRows(row, map, 0, new char[n-1], nextRows);
for (char[] next : nextRows) {
if (dfs(next, map, memo)) {
memo.put(key, true);
return true;
}
}
memo.put(key, false);
return false;
}
private void getNextRows(char[] row, List<Character>[][] map, int idx,
char[] current, List<char[]> result) {
if (idx == row.length - 1) {
result.add(current.clone());
return;
}
int a = row[idx] - 'A';
int b = row[idx + 1] - 'A';
if (map[a][b] == null) return;
for (char c : map[a][b]) {
current[idx] = c;
getNextRows(row, map, idx + 1, current, result);
}
}
}",0,leetcode,NA,JAVA
,"public class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(words == null || words.length == 0){
return res;
}
//build the map save the key-val pairs: String - idx
HashMap<String, Integer> map = new HashMap<>();
for(int i = 0; i < words.length; i++){
map.put(words[i], i);
}
//special cases: """" can be combine with any palindrome string
if(map.containsKey("""")){
int blankIdx = map.get("""");
for(int i = 0; i < words.length; i++){
if(isPalindrome(words[i])){
if(i == blankIdx) continue;
res.add(Arrays.asList(blankIdx, i));
res.add(Arrays.asList(i, blankIdx));
}
}
}
//find all string and reverse string pairs
for(int i = 0; i < words.length; i++){
String cur_r = reverseStr(words[i]);
if(map.containsKey(cur_r)){
int found = map.get(cur_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
}
//find the pair s1, s2 that
//case1 : s1[0:cut] is palindrome and s1[cut+1:] = reverse(s2) => (s2, s1)
//case2 : s1[cut+1:] is palindrome and s1[0:cut] = reverse(s2) => (s1, s2)
for(int i = 0; i < words.length; i++){
String cur = words[i];
for(int cut = 1; cut < cur.length(); cut++){
if(isPalindrome(cur.substring(0, cut))){
String cut_r = reverseStr(cur.substring(cut));
if(map.containsKey(cut_r)){
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(found, i));
}
}
if(isPalindrome(cur.substring(cut))){
String cut_r = reverseStr(cur.substring(0, cut));
if(map.containsKey(cut_r)){
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
}
}
}
return res;
}
public String reverseStr(String str){
StringBuilder sb= new StringBuilder(str);
return sb.reverse().toString();
}
public boolean isPalindrome(String s){
int i = 0;
int j = s.length() - 1;
while(i <= j){
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}",0,leetcode,NA,JAVA
,"import java.util.*;
public class Graph {
private List<List<Integer>> adjList;
public Graph(int vertices) {
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}
public void addEdge(int u, int v) {
adjList.get(u).add(v);
adjList.get(v).add(u); // undirected
}
public List<Integer> getNeighbors(int v) {
return adjList.get(v);
}
}
",1,PERPLEXITY,Create a Java graph representation using adjacency list with List<List<Integer>>,JAVA
,"public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
int[] numbers = new int[10];
for (int i = 0; i<secret.length(); i++) {
int s = Character.getNumericValue(secret.charAt(i));
int g = Character.getNumericValue(guess.charAt(i));
if (s == g) bulls++;
else {
if (numbers[s] < 0) cows++;
if (numbers[g] > 0) cows++;
numbers[s] ++;
numbers[g] --;
}
}
return bulls + ""A"" + cows + ""B"";
}",0,leetcode,NA,JAVA
,"public class MinHeapPQ {
private int[] heap;
private int size;
public MinHeapPQ(int capacity) {
heap = new int[capacity];
size = 0;
}
private void heapifyUp(int index) {
while (index > 0 && heap[(index - 1) / 2] > heap[index]) {
swap((index - 1) / 2, index);
index = (index - 1) / 2;
}
}
private void heapifyDown(int index) {
int smallest = index;
int left = 2 * index + 1; int right = 2 * index + 2;
if (left < size && heap[left] < heap[smallest]) smallest = left;
if (right < size && heap[right] < heap[smallest]) smallest = right;
if (smallest != index) { swap(index, smallest); heapifyDown(smallest); }
}
private void swap(int i, int j) { int temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; }
}
",1,PERPLEXITY,Implement a min-heap priority queue in Java for integers using an array,JAVA
,"class Solution {
public String frequencySort(String s) {
char str[] = s.toCharArray();
HashMap<Character,Integer> map = new HashMap<>();
for(char n:str){
map.put(n, map.getOrDefault(n, 0) + 1);
}
ArrayList<Character> list = new ArrayList<>(map.keySet());
Collections.sort(list, (a, b) -> map.get(b) - map.get(a));
StringBuilder sb = new StringBuilder();
for(char ch:list){
for(int i = 0; i < map.get(ch); i++){
sb.append(ch);
}
}
return sb.toString();
}
}",0,leetcode,NA,JAVA
,"import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class HttpGetClient {
public static String get(String url) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return response.body();
}
}
",1,PERPLEXITY,Write a Java method using HttpClient to make a GET request and return the response body as string,JAVA
,"public int numberOfBoomerangs(int[][] points) {
if(points == null || points.length == 0 || points[0].length == 0){
return 0;
}
int count = 0;
Map<Integer,Integer> hashMap = new HashMap<>();
for (int i = 0;i < points.length;i++){
//count distances for every i with an empty hashMap,and hashMap.clear() is more faster than new HashMap()
hashMap.clear();
for (int j = 0;j < points.length;j++){
//it's unnecessary when i == j
if (i == j){
continue;
}
//multiple them directly is more faster than use Math.pow()
int distance = (points[j][0]-points[i][0])*(points[j][0]-points[i][0]) + (points[j][1]-points[i][1]) * (points[j][1]-points[i][1]);
//First, select one position to place your new point by distance with number of hashMap.get(distance)
//and then you can change the order of the two elements,so multiple 2
count += hashMap.getOrDefault(distance,0) * 2;
hashMap.put(distance,hashMap.getOrDefault(distance,0) + 1);
}
}
return count;
}",0,leetcode,NA,JAVA
,"import java.util.Base64;
public class Base64Util {
public static String encode(String input) {
byte[] encoded = Base64.getEncoder().encode(input.getBytes());
return new String(encoded);
}
public static String decode(String encoded) {
byte[] decoded = Base64.getDecoder().decode(encoded.getBytes());
return new String(decoded);
}
}
",1,PERPLEXITY,Create a Java utility class with static methods to encode and decode strings using Base64.,JAVA
,"class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
int num = Math.abs(nums[i]);
if (nums[num - 1] > 0) {
nums[num - 1] *= -1;
} else {
ans.add(num);
}
}
return ans;
}
}",0,leetcode,NA,JAVA
,"import java.util.regex.Pattern;
public class EmailValidator {
private static final Pattern EMAIL_PATTERN =
Pattern.compile(""^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$"");
public static boolean isValid(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
}
",1,PERPLEXITY,Write a Java method with regex pattern to validate email addresses comprehensively,JAVA
,"class Solution {
public List<Integer> findAnagrams(String s, String p) {
ArrayList<Integer> ans= new ArrayList<>();
int pfreq []=new int [256];
int sfreq []=new int [256];
int low=0;
int len=0;
for(int i=0;i<p.length(); i++){
pfreq[p.charAt(i)]++;
}
for(int high=0; high<s.length(); high++){
sfreq[s.charAt(high)]++;
len=high-low+1;
while(len>p.length()){
sfreq[s.charAt(low)]--;
low++;
len = high - low + 1;
}
if(isAnagram(sfreq,pfreq)){
ans.add(low);
}
}
return ans;
}
public boolean isAnagram(int []sfreq, int [] pfreq){
for(int i=0;i<256; i++ ){
if(pfreq[i]!=sfreq[i]){
return false;
}
}
return true;
}
}",0,leetcode,NA,JAVA
,"import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileReaderUtil {
public static List<String> readFile(String path) throws Exception {
try (var lines = Files.newBufferedReader(Paths.get(path))) {
return Files.readAllLines(Paths.get(path));
}
}
}
",1,PERPLEXITY,"Create a Java method to read all lines from a file using try-with-resources and return as List.""",JAVA
,"import java.util.*;
class AllOne {
// Bucket node for doubly linked list
private static class Bucket {
int count;
Set<String> keys;
Bucket prev, next;
Bucket(int count) {
this.count = count;
this.keys = new HashSet<>();
}
}
private Bucket head, tail;
private Map<String, Bucket> keyToBucket;
public AllOne() {
head = new Bucket(0); // dummy head
tail = new Bucket(0); // dummy tail
head.next = tail;
tail.prev = head;
keyToBucket = new HashMap<>();
}
public void inc(String key) {
if (!keyToBucket.containsKey(key)) {
// insert new key with count = 1
Bucket first = head.next;
if (first != tail && first.count == 1) {
first.keys.add(key);
keyToBucket.put(key, first);
} else {
Bucket newBucket = new Bucket(1);
newBucket.keys.add(key);
insertAfter(head, newBucket);
keyToBucket.put(key, newBucket);
}
} else {
Bucket curr = keyToBucket.get(key);
Bucket next = curr.next;
if (next != tail && next.count == curr.count + 1) {
next.keys.add(key);
keyToBucket.put(key, next);
} else {
Bucket newBucket = new Bucket(curr.count + 1);
newBucket.keys.add(key);
insertAfter(curr, newBucket);
keyToBucket.put(key, newBucket);
}
curr.keys.remove(key);
if (curr.keys.isEmpty()) {
remove(curr);
}
}
}
public void dec(String key) {
Bucket curr = keyToBucket.get(key);
if (curr.count == 1) {
// remove key completely
curr.keys.remove(key);
keyToBucket.remove(key);
if (curr.keys.isEmpty()) {
remove(curr);
}
} else {
Bucket prev = curr.prev;
if (prev != head && prev.count == curr.count - 1) {
prev.keys.add(key);
keyToBucket.put(key, prev);
} else {
Bucket newBucket = new Bucket(curr.count - 1);
newBucket.keys.add(key);
insertAfter(curr.prev, newBucket);
keyToBucket.put(key, newBucket);
}
curr.keys.remove(key);
if (curr.keys.isEmpty()) {
remove(curr);
}
}
}
public String getMaxKey() {
if (tail.prev == head) return """";
return tail.prev.keys.iterator().next();
}
public String getMinKey() {
if (head.next == tail) return """";
return head.next.keys.iterator().next();
}
// Doubly linked list helpers
private void insertAfter(Bucket prev, Bucket node) {
node.prev = prev;
node.next = prev.next;
prev.next.prev = node;
prev.next = node;
}
private void remove(Bucket node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
}
/**
* Your AllOne object will be instantiated and called as such:
* AllOne obj = new AllOne();
* obj.inc(key);
* obj.dec(key);
* String param_3 = obj.getMaxKey();
* String param_4 = obj.getMinKey();
*/",0,leetcode,NA,JAVA
,"import java.util.UUID;
public class UUIDUtil {
public static String generate() {
return UUID.randomUUID().toString();
}
public static boolean isValid(String uuid) {
try {
UUID.fromString(uuid);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
",1,PERPLEXITY,Implement a Java utility to generate UUID v4 strings and validate their format,JAVA
,"class Solution {
public String originalDigits(String s) {
int[] charCount = new int[26];
for (char c : s.toCharArray()) {
charCount[c - 'a']++;
}
int[] digitCount = new int[10];
digitCount[0] = charCount['z' - 'a'];
digitCount[2] = charCount['w' - 'a'];
digitCount[4] = charCount['u' - 'a'];
digitCount[6] = charCount['x' - 'a'];
digitCount[8] = charCount['g' - 'a'];
digitCount[3] = charCount['h' - 'a'] - digitCount[8];
digitCount[5] = charCount['f' - 'a'] - digitCount[4];
digitCount[7] = charCount['s' - 'a'] - digitCount[6];
digitCount[1] = charCount['o' - 'a'] - digitCount[0] - digitCount[2] - digitCount[4];
digitCount[9] = charCount['i' - 'a'] - digitCount[5] - digitCount[6] - digitCount[8];
StringBuilder result = new StringBuilder();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < digitCount[i]; j++) {
result.append(i);
}
}
return result.toString();
}
}",0,leetcode,NA,JAVA
,"import java.util.*;
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> deadendSet = new HashSet<>(Arrays.asList(deadends));
if (deadendSet.contains(""0000"")) {
return -1;
}
Queue<Pair<String, Integer>> queue = new LinkedList<>();
queue.offer(new Pair<>(""0000"", 0));
Set<String> visited = new HashSet<>();
visited.add(""0000"");
while (!queue.isEmpty()) {
Pair<String, Integer> current = queue.poll();
String currentCombination = current.getKey();
int moves = current.getValue();
if (currentCombination.equals(target)) {
return moves;
}
for (int i = 0; i < 4; i++) {
for (int delta : new int[]{-1, 1}) {
int newDigit = (currentCombination.charAt(i) - '0' + delta + 10) % 10;
String newCombination = currentCombination.substring(0, i) +
newDigit +
currentCombination.substring(i + 1);
if (!visited.contains(newCombination) && !deadendSet.contains(newCombination)) {
visited.add(newCombination);
queue.offer(new Pair<>(newCombination, moves + 1));
}
}
}
}
return -1; // Target is not reachable
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int longestPalindrome(String s) {
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
int cnt=0;
Boolean odd=false;
for(char ch : s.toCharArray())
hm.put(ch, hm.getOrDefault(ch,0)+1 );
for(int i : hm.values())
{
if(i%2==0)
cnt+=i;
else
{
cnt+=i-1;
odd =true;
}
}
if(odd)
return ++cnt;
else
return cnt;
}
}class Solution {
public int longestPalindrome(String s) {
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
int cnt=0;
Boolean odd=false;
for(char ch : s.toCharArray())
hm.put(ch, hm.getOrDefault(ch,0)+1 );
for(int i : hm.values())
{
if(i%2==0)
cnt+=i;
else
{
cnt+=i-1;
odd =true;
}
}
if(odd)
return ++cnt;
else
return cnt;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
HashMap<Integer,Integer> map =new HashMap<>();
int count=0;
for(int a:nums1)
{
for(int b:nums2)
{
int sum=a+b;
map.put(sum,map.getOrDefault(sum,0)+1);
}
}
for(int c : nums3)
{
for(int d:nums4)
{
int sum=c+d;
if(map.containsKey(-sum))
{
count += map.get(-sum);
}
}
}
return count;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean isRectangleCover(int[][] rectangles) {
TreeSet<int[]> set = new TreeSet<int[]>((a, b) -> {
if (a[3] <= b[1]) return -1;
else if (a[1] >= b[3]) return 1;
else if (a[2] <= b[0]) return -1;
else if (a[0] >= b[2]) return 1;
else return 0;
});
int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE;
int maxA = Integer.MIN_VALUE, maxB = Integer.MIN_VALUE;
int totalArea = 0;
for (int[] i : rectangles) {
if (i[0] < minX) {
minX = i[0];
} if (i[1] < minY) {
minY = i[1];
} if (i[2] > maxA) {
maxA = i[2];
} if (i[3] > maxB) {
maxB = i[3];
}
totalArea += (i[2] - i[0]) * (i[3] - i[1]);
if (!set.add(i)) return false;
}
return totalArea == (maxA - minX) * (maxB - minY);
}
}",0,leetcode,NA,JAVA
,"public enum Singleton {
INSTANCE;
private Singleton() {}
public void doSomething() {
System.out.println(""Singleton instance method"");
}
public static Singleton getInstance() {
return INSTANCE;
}
}
",1,PERPLEXITY,Write a thread-safe singleton class in Java using enum pattern,JAVA
,"class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote.length() > magazine.length()) return false;
int[] alphabets_counter = new int[26];
for (char c : magazine.toCharArray())
alphabets_counter[c-'a']++;
for (char c : ransomNote.toCharArray()){
if (alphabets_counter[c-'a'] == 0) return false;
alphabets_counter[c-'a']--;
}
return true;
}
}",0,leetcode,NA,JAVA
,"interface Shape { void draw(); }
class Circle implements Shape {
public void draw() { System.out.println(""Drawing Circle""); }
}
class Rectangle implements Shape {
public void draw() { System.out.println(""Drawing Rectangle""); }
}
public class ShapeFactory {
public static Shape createShape(String type) {
switch (type.toLowerCase()) {
case ""circle"": return new Circle();
case ""rectangle"": return new Rectangle();
default: throw new IllegalArgumentException(""Unknown shape"");
}
}
}
",1,PERPLEXITY,Create a Java factory method pattern to create different Shape objects based on string input,JAVA
,"class Solution {
public int findLUSlength(String[] strs) {
int n = strs.length;
int len = -1;
HashSet<String> set = new HashSet<>();
for(int i =0;i<n;i++){
String str = strs[i];
if(!set.contains(str)){
boolean possibilities = true;
for(int j=0;j<n;j++)
{
if(i == j) continue;
String temp = strs[j];
if(str.equals(temp)) {
set.add(str);
set.add(temp);
possibilities = false;
break;
}
int len1 = str.length();
int len2 = temp.length();
int p =0;int q=0;
while(p < len1 && q < len2){
if(str.charAt(p) == temp.charAt(q)){
p++;
q++;
}else q++;
}
if(p == len1) possibilities = false;
}
if(possibilities) len = Math.max(len, str.length());
}
}
return len;
}
}",0,leetcode,NA,JAVA
,"public class Solution {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int j = 0;
int maxLength = 0;
for (int i = 0; i < nums.length; i++) {
while (nums[i] - nums[j] > 1) {
j++;
}
if (nums[i] - nums[j] == 1) {
maxLength = Math.max(maxLength, i - j + 1);
}
}
return maxLength;
}
}",0,leetcode,NA,JAVA
,"class Solution {
int i=0,j=0;
int m=0;int n=0;
public Solution(int m, int n) {
this.m=m;
this.n=n;
}
public int[] flip() {
j++;
if(j==n){
j=0;
i++;
}
if(i==m){
i=0;
j=0;
}
return new int[]{i,j};
}
public void reset() {
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(m, n);
* int[] param_1 = obj.flip();
* obj.reset();
*/",0,leetcode,NA,JAVA
,"class WordFilter {
constructor(words) {
this.pTrie = new Array(27)
this.sTrie = new Array(27)
let wordSet = new Set()
for (let index = words.length - 1; ~index; index--) {
let word = words[index], wlen = word.length
if (wordSet.has(word))
continue;
wordSet.add(word)
this.insert(word, index, this.pTrie, 0, wlen, 1)
this.insert(word, index, this.sTrie, wlen-1, -1, -1)
}
}
insert(word, index, trie, start, end, step) {
for (let i = start; i != end; i += step) {
let c = word.charCodeAt(i) - 97
if (!trie[c]) trie[c] = new Array(27)
trie = trie[c]
if (!trie[26]) trie[26] = []
trie[26].push(index)
}
}
retrieve(word, trie, start, end, step) {
for (let i = start; i != end; i += step) {
let c = word.charCodeAt(i) - 97
if (!trie[c]) return []
trie = trie[c]
}
return trie[26]
}
f(pre, suf) {
let pVals = this.retrieve(pre, this.pTrie, 0, pre.length, 1),
sVals = this.retrieve(suf, this.sTrie, suf.length-1, -1, -1),
svix = 0, pvix = 0
while (svix < sVals.length && pvix < pVals.length) {
let sVal = sVals[svix], pVal = pVals[pvix]
if (sVal === pVal) return sVal
sVal > pVal ? svix++ : pvix++
}
return -1
}
};",0,leetcode,NA,JAVA
,"class Solution {
int maxF=0;
List<Integer> maxSumArr = new ArrayList<>();
Map<Integer, Integer> f = new HashMap<>();
public int[] findFrequentTreeSum(TreeNode root) {
solve(root);
int[] arr = new int[maxSumArr.size()];
for(int i=0; i<arr.length; i++){
arr[i] = maxSumArr.get(i);
}
return arr;
}
public int solve(TreeNode root){
if(root == null) return 0;
int sum = root.val + solve(root.left) + solve(root.right);
f.put(sum , f.getOrDefault(sum, 0) + 1);
if(f.get(sum) > maxF){
maxSumArr.clear();
maxSumArr.add(sum);
maxF = f.get(sum);
}else if(f.get(sum) == maxF){
maxSumArr.add(sum);
}
return sum;
}
}",0,leetcode,NA,JAVA
,"import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers = new ArrayList<>();
private int state;
public int getState() { return state; }
public void setState(int state) {
this.state = state;
notifyObservers();
}
public void attach(Observer observer) { observers.add(observer); }
public void notifyObservers() {
for (Observer o : observers) o.update();
}
}
interface Observer { void update(); }
",1,PERPLEXITY,Implement observer pattern in Java with Subject and Observer interfaces,JAVA
,"class Solution {
public String[] findWords(String[] words) {
ArrayList<String> ans=new ArrayList<>();
String first = ""qwertyuiop"";
String Secound =""asdfghjkl"";
String Third=""zxcvbnm"";
for(String i : words){
if(isinrow(i,first) || isinrow(i,Secound) || isinrow(i,Third))
ans.add(i);
}
return ans.toArray(new String[0]);
}
private boolean isinrow(String s,String row){
for(char c:s.toCharArray()){
if(row.indexOf(Character.toLowerCase(c))==-1){
return false;
}
}
return true;
}
}",0,leetcode,NA,JAVA
,"public int deleteAndEarn(int[] nums) {
var numToCount = new HashMap<Integer, Integer>();
var min = Integer.MAX_VALUE;
var max = Integer.MIN_VALUE;
for (var num : nums) {
numToCount.compute(num, (k, v) -> v == null ? 1 : ++v);
min = Math.min(min, num);
max = Math.max(max, num);
}
var prevIncEarn = 0;
var prevExcEarn = 0;
for (var i = min; i <= max; i++) {
var incEarn = prevExcEarn + i * numToCount.getOrDefault(i, 0);
var excEarn = Math.max(prevIncEarn, prevExcEarn);
prevIncEarn = incEarn;
prevExcEarn = excEarn;
}
return Math.max(prevIncEarn, prevExcEarn);
}",0,leetcode,NA,JAVA
,"class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] ans = new int[nums1.length];
Arrays.fill(ans, -1);
int index = 0;
for(int i=0; i<nums1.length; i++){
for(int j=0; j<nums2.length; j++){
if(nums1[i] == nums2[j]){
for(int k=j; k<nums2.length; k++){
if(nums2[k] > nums2[j]){
ans[i] = nums2[k];
break;
}
}
}
}
}
return ans;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
Map<Integer,Integer> map=new HashMap<>();
for (int i=0; i<indices.length; i++){
if (s.startsWith(sources[i],indices[i])){
map.put(indices[i],i);
}
}
StringBuilder sb=new StringBuilder();
for (int i=0; i<s.length();){
if (!map.containsKey(i)){
sb.append(s.charAt(i));
i++;
} else { //replace chars
sb.append(targets[map.get(i)]);
i+=sources[map.get(i)].length();
}
}
return sb.toString();
}
}",0,leetcode,NA,JAVA
,"class Solution {
int[] arr;
HashSet<List<Integer>> hashSet = new HashSet<>();
public List<List<Integer>> findSubsequences(int[] nums) {
arr = nums;
List<Integer> arrayList = new ArrayList<>();
recursion(arrayList,0);
List<List<Integer>> result = new ArrayList<>(hashSet);
return result;
}
public void recursion(List<Integer> arrayList, int index){
if(arrayList.size()>=2) hashSet.add(new ArrayList(arrayList));
for(int i = index;i<arr.length;i++){
if(arrayList.size() == 0 || arr[i]>= arrayList.get(arrayList.size()-1)){
arrayList.add(arr[i]);
recursion(arrayList,i+1);
arrayList.remove(arrayList.size()-1);
}
}
}
}",0,leetcode,NA,JAVA
,"interface SortStrategy { void sort(int[] arr); }
class BubbleSortStrategy implements SortStrategy {
public void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;
}
}
}
}
}
public class Sorter {
private SortStrategy strategy;
public void setStrategy(SortStrategy strategy) { this.strategy = strategy; }
public void sort(int[] arr) { strategy.sort(arr); }
}
",1,PERPLEXITY,Create strategy pattern in Java for different sorting algorithms.,JAVA
,"class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length == 0)
return new double[0];
Node root = null;
for (int i = 0; i < k; i++) {
root = insert(root, nums[i]);
}
double[] r = new double[nums.length - k + 1];
boolean even = k % 2 == 0;
int j = 0;
for (int i = k; i <= nums.length; i++) {
double sum = 0.0;
if (even)
sum = (findSmallest(root, k/2).val + findSmallest(root, k/2 + 1).val) / 2.0;
else
sum = findSmallest(root, k/2 + 1).val;
r[j++] = sum;
if (i < nums.length) {
root = insert(root, nums[i]);
root = delete(root, nums[i - k]);
}
}
return r;
}
private Node findSmallest(Node root, int k) {
int s = countWith(root.left) + 1;
if (s == k)
return root;
if (s > k) {
return findSmallest(root.left, k);
}
return findSmallest(root.right, k - s);
}
private Node delete(Node root, long val) {
if (root == null)
return null;
else if (val > root.val)
root.right = delete(root.right, val);
else if (val < root.val)
root.left = delete(root.left, val);
else {
if (root.left == null)
root = root.right;
else if (root.right == null)
root = root.left;
else {
Node t = findMin(root.right);
root.val = t.val;
root.right = delete(root.right, t.val);
}
}
return updateNode(root);
}
private Node findMin(Node root) {
if (root.left != null)
return findMin(root.left);
return root;
}
private Node insert(Node root, long val)
{
if (root == null)
{
return new Node(val);
}
if (val >= root.val)
{
root.right = insert(root.right, val);
}
else
{
root.left = insert(root.left, val);
}
return updateNode(root);
}
private Node updateNode(Node root) {
int b = balance(root);
if (b == 2 && balance(root.left) < 0)
{
root.left = leftRotate(root.left);
root = rightRotate(root);
}
else if (b == -2 && balance(root.right) > 0)
{
root.right = rightRotate(root.right);
root = leftRotate(root);
}
else if (b == 2)
{
root = rightRotate(root);
}
else if (b == -2)
{
root = leftRotate(root);
}
update(root);
return root;
}
private Node leftRotate(Node n)
{
Node r = n.right;
n.right = r.left;
r.left = n;
update(n);
update(r);
return r;
}
private Node rightRotate(Node n)
{
Node l = n.left;
n.left = l.right;
l.right = n;
update(n);
update(l);
return l;
}
private int balance(Node n)
{
if (n==null)return 0;
return height(n.left) - height(n.right);
}
private void update(Node n)
{
if (n==null)return;
n.height = Math.max(height(n.left), height(n.right)) + 1;
n.count = n.left != null ? n.left.count + 1 : 0;
n.count += n.right != null ? n.right.count + 1 : 0;
}
private int height(Node n)
{
return n != null ? n.height : 0;
}
private int countWith(Node n)
{
return n != null ? n.count + 1 : 0;
}
static class Node
{
Node left;
Node right;
long val;
int count;
int height;
Node(long val)
{
this.val = val;
}
}
}",0,leetcode,NA,JAVA
,"public class User {
private String name, email, phone;
private int age;
private User(Builder builder) {
this.name = builder.name;
this.email = builder.email;
this.phone = builder.phone;
this.age = builder.age;
}
public static class Builder {
private String name, email, phone;
private int age;
public Builder name(String name) { this.name = name; return this; }
public Builder email(String email) { this.email = email; return this; }
public Builder phone(String phone) { this.phone = phone; return this; }
public Builder age(int age) { this.age = age; return this; }
public User build() { return new User(this); }
}
}
",1,PERPLEXITY,Write Java builder pattern for a complex User object with multiple optional fields,JAVA
,"class LFUCache {
public LFUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!keyToVal.containsKey(key))
return -1;
final int freq = keyToFreq.get(key);
freqToLRUKeys.get(freq).remove(key);
if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) {
freqToLRUKeys.remove(freq);
++minFreq;
}
// Increase key's freq by 1
// Add this key to next freq's list
putFreq(key, freq + 1);
return keyToVal.get(key);
}
public void put(int key, int value) {
if (capacity == 0)
return;
if (keyToVal.containsKey(key)) {
keyToVal.put(key, value);
get(key); // Update key's count
return;
}
if (keyToVal.size() == capacity) {
// Evict LRU key from the minFreq list
final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next();
freqToLRUKeys.get(minFreq).remove(keyToEvict);
keyToVal.remove(keyToEvict);
}
minFreq = 1;
putFreq(key, minFreq); // Add new key and freq
keyToVal.put(key, value); // Add new key and value
}
private int capacity;
private int minFreq = 0;
private Map<Integer, Integer> keyToVal = new HashMap<>();
private Map<Integer, Integer> keyToFreq = new HashMap<>();
private Map<Integer, LinkedHashSet<Integer>> freqToLRUKeys = new HashMap<>();
private void putFreq(int key, int freq) {
keyToFreq.put(key, freq);
freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>());
freqToLRUKeys.get(freq).add(key);
}
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean circularArrayLoop(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
int slow = i, fast = i;
boolean forward = nums[i] > 0;
while (true) {
slow = next(nums, slow);
if ((nums[slow] > 0) != forward) break;
fast = next(nums, fast);
if ((nums[fast] > 0) != forward) break;
fast = next(nums, fast);
if ((nums[fast] > 0) != forward) break;
if (slow == fast) {
if (slow == next(nums, slow)) break;
return true;
}
}
}
return false;
}
private int next(int[] nums, int i) {
int n = nums.length;
int next = (i + nums[i]) % n;
if (next < 0) next += n;
return next;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int numFactoredBinaryTrees(int[] arr) {
Arrays.sort(arr);
Map<Integer, Long> subtreeCount = new HashMap<>();
for (int root : arr) {
subtreeCount.put(root, 1L);
for (int factor : arr) {
if (factor >= root) {
break;
}
if (root % factor == 0 && subtreeCount.containsKey(root / factor)) {
subtreeCount.put(root, (subtreeCount.get(root) + subtreeCount.get(factor) * subtreeCount.get(root / factor)));
}
}
}
long totalTrees = 0L;
for (int key : subtreeCount.keySet()) {
totalTrees = (totalTrees + subtreeCount.get(key)) % 1_000_000_007;
}
return (int) totalTrees;
}
}",0,leetcode,NA,JAVA
,"// 6 ms. 98.66%
public int distributeCandies(int[] candyType) {
BitSet bits = new BitSet(200001);
int count = 0, max = candyType.length / 2;
for(int candy: candyType) {
int t = candy + 100000;
if(!bits.get(t)) {
if(++count == max) return max;
bits.set(t);
}
}
return count;
}",0,leetcode,NA,JAVA
,"public int flipgame(int[] f, int[] b) {
HashSet<Integer> same = new HashSet<>();
for (int i = 0; i < f.length; ++i)
if (f[i] == b[i])
same.add(f[i]);
int res = 3000;
for (int i : f)
if (!same.contains(i))
res = Math.min(res, i);
for (int i : b)
if (!same.contains(i))
res = Math.min(res, i);
return res % 3000;
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean checkInclusion(String s1, String s2) {
if (s1.length() > s2.length()) {
return false;
}
HashMap<Character, Integer> s1Count = new HashMap<>();
HashMap<Character, Integer> s2Count = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
s1Count.put(s1.charAt(i), s1Count.getOrDefault(s1.charAt(i), 0) + 1);
s2Count.put(s2.charAt(i), s2Count.getOrDefault(s2.charAt(i), 0) + 1);
}
if (s1Count.equals(s2Count)) {
return true;
}
int left = 0;
for (int right = s1.length(); right < s2.length(); right++) {
char charRight = s2.charAt(right);
s2Count.put(charRight, s2Count.getOrDefault(charRight, 0) + 1);
char charLeft = s2.charAt(left);
s2Count.put(charLeft, s2Count.get(charLeft) - 1);
if (s2Count.get(charLeft) == 0) {
s2Count.remove(charLeft);
}
left++;
if (s1Count.equals(s2Count)) {
return true;
}
}
return false;
}
}",0,leetcode,NA,JAVA
,"public class NumberPrinter implements Runnable {
private int id;
public NumberPrinter(int id) { this.id = id; }
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(""Thread "" + id + "": "" + i);
try { Thread.sleep(100); } catch (InterruptedException e) {}
}
}
}
",1,PERPLEXITY,Create a Java Thread class that implements Runnable to print numbers from 1 to 10,JAVA
,"class Solution {
public int subarraySum(int[] nums, int k) {
HashMap<Integer, Integer> subNum = new HashMap<>();
subNum.put(0, 1);
int total = 0, count = 0;
for (int n : nums) {
total += n;
if (subNum.containsKey(total - k)) {
count += subNum.get(total - k);
}
subNum.put(total, subNum.getOrDefault(total, 0) + 1);
}
return count;
}
}",0,leetcode,NA,JAVA
,"class TrieNode {
TrieNode[] branch = new TrieNode[26];
Boolean isEmpty = true;
}
class Solution {
public int minimumLengthEncoding(String[] W) {
TrieNode trie = new TrieNode();
trie.branch = new TrieNode[26];
int ans = 1;
for (String word : W) {
TrieNode curr = trie;
Boolean newWord = false;
for (int i = word.length() - 1; i >= 0; i--) {
int c = word.charAt(i) - 'a';
if (curr.isEmpty && !newWord) ans -= word.length() - i;
if (curr.branch[c] == null) {
curr.branch[c] = new TrieNode();
newWord = true;
curr.isEmpty = false;
}
curr = curr.branch[c];
}
if (newWord) ans += word.length() + 1;
}
return ans;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int leastBricks(List<List<Integer>> wall)
{
HashMap<Integer, Integer> edge_frequency = new HashMap<>(); // HashMap to store the number of common edges among the rows
int max_frequency = 0; // Variable to store the frequency of most occuring edge
for(int row=0; row<wall.size(); row++) // Iterating through each row
{
int edge_postion = 0; // Variable to store different edge postion
for(int brick_no=0; brick_no<wall.get(row).size()-1; brick_no++) // Iterating through each brick inside a row
{
int current_brick_length = wall.get(row).get(brick_no); // Length of the current brick
edge_postion = edge_postion + current_brick_length; // Next Edge Position = Previous Edge Position + Current Brick's Length
edge_frequency.put(edge_postion,edge_frequency.getOrDefault(edge_postion,0)+1); // Incrementing the Frequency of just calculated Edge Postion
max_frequency = Math.max(edge_frequency.get(edge_postion), max_frequency); // Comparing the ""Frequency of just calculated Edge Postion"" with ""Max Frequency seen till now"" & storing whichever is greater.
}
}
return wall.size() - max_frequency; // returning (Number of Bricks Crossed by Line) i.e. (Number of Rows in Wall - Frequency of Most Occuring Edge)
}
}",0,leetcode,NA,JAVA
,"import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 5; i++) {
int taskId = i;
executor.submit(() -> {
System.out.println(""Task "" + taskId + "" executed by "" +
Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
",1,PERPLEXITY,Write Java code using ExecutorService to execute 5 tasks in a thread pool.,JAVA
,"public class Codec {
Map<String, String> codeDB = new HashMap<>(), urlDB = new HashMap<>();
static final String chars = ""0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"";
private String getCode() {
char[] code = new char[6];
for (int i = 0; i < 6; i++)
code[i] = chars.charAt((int)(Math.random() * 62));
return ""http://tinyurl.com/"" + String.valueOf(code);
}
public String encode(String longUrl) {
if (urlDB.containsKey(longUrl)) return urlDB.get(longUrl);
String code = getCode();
while (codeDB.containsKey(code)) code = getCode();
codeDB.put(code, longUrl);
urlDB.put(longUrl, code);
return code;
}
public String decode(String shortUrl) {
return codeDB.get(shortUrl);
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int numComponents(ListNode head, int[] nums) {
Set<Integer> set = new HashSet<>();
for (int x : nums) set.add(x);
ListNode curr = head;
int count = 0;
while (curr != null) {
// If current node is in set and (it's the last node OR next node is not in set)
if (set.contains(curr.val) && (curr.next == null || !set.contains(curr.next.val))) {
count++;
}
curr = curr.next;
}
return count;
}
}",0,leetcode,NA,JAVA
,"// O(n) Time Solution
class Solution {
public int findPairs(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap();
for (int num : nums)
map.put(num, map.getOrDefault(num, 0) + 1);
int result = 0;
for (int i : map.keySet())
if (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1)
result++;
return result;
}
}",0,leetcode,NA,JAVA
,"import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static CompletableFuture<String> processAsync(int input) {
return CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(1000); } catch (Exception e) {}
return ""Processed: "" + input;
}).thenApply(result -> result.toUpperCase());
}
}
",1,PERPLEXITY,Create a Java CompletableFuture example that chains two asynchronous operations,JAVA
,"class Solution {
public int findMaxLength(int[] nums) {
// Map to store first occurrence of diff
HashMap<Integer, Integer> map = new HashMap<>();
int zero = 0, one = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0)
zero++;
else
one++;
int diff = zero - one;
// If diff == 0, subarray from 0 to i is valid
if (diff == 0) {
res = Math.max(res, i + 1);
}
// If diff not seen before, store index
if (!map.containsKey(diff)) {
map.put(diff, i);
}
// If seen before, calculate length
else {
int idx = map.get(diff);
int len = i - idx;
res = Math.max(res, len);
}
}
return res;
}
}",0,leetcode,NA,JAVA
,"import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private static Semaphore semaphore = new Semaphore(3);
public static void accessResource(int id) {
try {
semaphore.acquire();
System.out.println(""Resource accessed by "" + id);
Thread.sleep(2000);
} catch (InterruptedException e) {}
finally { semaphore.release(); }
}
}
",1,PERPLEXITY,Implement a semaphore in Java to limit concurrent access to 3 resources,JAVA
,"class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
// maintain a hash map to store <sum % k, index>
Map<Integer, Integer> map = new HashMap<>();
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
sum %= k;
// case 1
if (sum == 0 && i > 0) {
return true;
}
// case 2
if (map.containsKey(sum) && i - map.get(sum) > 1) {
return true;
}
if (!map.containsKey(sum)) {
map.put(sum, i);
}
}
return false;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) {
return 0;
}
int maxStop = -1;
for (int[] route : routes) {
for (int stop : route) {
maxStop = Math.max(maxStop, stop);
}
}
if (maxStop < target) {
return -1;
}
int n = routes.length;
int[] minBusesToReach = new int[maxStop + 1];
Arrays.fill(minBusesToReach, n + 1);
minBusesToReach[source] = 0;
boolean flag = true;
while (flag) {
flag = false;
for (int[] route : routes) {
int min = n + 1;
for (int stop : route) {
min = Math.min(min, minBusesToReach[stop]);
}
min++;
for (int stop : route) {
if (minBusesToReach[stop] > min) {
minBusesToReach[stop] = min;
flag = true;
}
}
}
}
return (minBusesToReach[target] < n + 1 ? minBusesToReach[target] : -1);
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int findLUSlength(String[] strs) {
int n = strs.length;
int len = -1;
HashSet<String> set = new HashSet<>();
for(int i =0;i<n;i++){
String str = strs[i];
if(!set.contains(str)){
boolean possibilities = true;
for(int j=0;j<n;j++)
{
if(i == j) continue;
String temp = strs[j];
if(str.equals(temp)) {
set.add(str);
set.add(temp);
possibilities = false;
break;
}
int len1 = str.length();
int len2 = temp.length();
int p =0;int q=0;
while(p < len1 && q < len2){
if(str.charAt(p) == temp.charAt(q)){
p++;
q++;
}else q++;
}
if(p == len1) possibilities = false;
}
if(possibilities) len = Math.max(len, str.length());
}
}
return len;
}
}",0,leetcode,NA,JAVA
,"import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static int sumSquares(List<Integer> numbers) {
return numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.reduce(0, Integer::sum);
}
}
",1,PERPLEXITY,"""Write Java stream operations to filter even numbers, map to squares, and reduce to sum.",JAVA
,"class Solution {
int i=0,j=0;
int m=0;int n=0;
public Solution(int m, int n) {
this.m=m;
this.n=n;
}
public int[] flip() {
j++;
if(j==n){
j=0;
i++;
}
if(i==m){
i=0;
j=0;
}
return new int[]{i,j};
}
public void reset() {
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(m, n);
* int[] param_1 = obj.flip();
* obj.reset();
*/",0,leetcode,NA,JAVA
,"import java.util.*;
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> map = new HashMap<>();
for (String domainCount : cpdomains) {
int spaceIndex = domainCount.indexOf(' ');
int count = Integer.parseInt(domainCount.substring(0, spaceIndex));
String domain = domainCount.substring(spaceIndex + 1);
// Process each subdomain
while (true) {
map.merge(domain, count, Integer::sum);
int dotIndex = domain.indexOf('.');
if (dotIndex == -1) break;
domain = domain.substring(dotIndex + 1);
}
}
List<String> result = new ArrayList<>(map.size());
for (Map.Entry<String, Integer> entry : map.entrySet()) {
result.add(entry.getValue() + "" "" + entry.getKey());
}
return result;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String,Integer> map = new HashMap<>();
for(String ch:words){
map.put(ch,map.getOrDefault(ch,0)+1);
}
PriorityQueue<Pair> pq = new PriorityQueue<>((a,b) -> {
if(a.freq!=b.freq){
return b.freq - a.freq;
}
return a.ch.compareTo(b.ch);
});
for (Map.Entry<String, Integer> entry : map.entrySet()) {
pq.add(new Pair(entry.getKey(), entry.getValue()));
}
List<String> ans = new ArrayList<>();
while(!pq.isEmpty() && k >0){
Pair curr = pq.poll();
ans.add(curr.ch);
k--;
}
return ans;
}
}
class Pair{
String ch;
int freq;
Pair(String ch,int freq){
this.ch = ch;
this.freq = freq;
}
}",0,leetcode,NA,JAVA
,"import java.util.*;
public class LambdaComparator {
public static void sortStrings(List<String> list) {
list.sort((s1, s2) -> {
if (s1.length() != s2.length())
return s1.length() - s2.length();
return s1.compareTo(s2);
});
}
}
",1,PERPLEXITY,Create a lambda comparator to sort a list of strings by length then alphabetically.,JAVA
,"class Solution {
public int minStickers(String[] stickers, String target) {
int n = stickers.length;
target = sortChars(target);
for (int i = 0; i < n; ++i) stickers[i] = sortChars(stickers[i]);
Queue<String> q = new LinkedList();
q.offer(target);
int steps = 0;
Set<String> visited = new HashSet<>();
while (!q.isEmpty()) {
steps++;
int size = q.size();
while(size-- > 0) {
String x = q.poll();
for (int i = 0; i < n; ++i) {
String now = filter(x, stickers[i]);
if (now.isEmpty()) return steps;
if (!now.equals(x) && !visited.contains(now)) {
visited.add(now);
q.offer(now);
}
}
}
}
return -1;
}
public String filter(String a, String b) {
StringBuilder ret = new StringBuilder();
int idx = 0;
for (char c : a.toCharArray()) {
boolean found = false;
while (idx < b.length() && b.charAt(idx) <= c) {
if (b.charAt(idx++) == c) {
found = true;
break;
}
}
if (!found) ret.append(c);
}
return ret.toString();
}
private String sortChars(String s) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}
",0,leetcode,NA,JAVA
,"import java.util.Optional;
public class OptionalExample {
public static String getEmail(User user) {
return Optional.ofNullable(user)
.map(User::getEmail)
.filter(email -> !email.isEmpty())
.orElse(""no-email@domain.com"");
}
}
class User { private String email; public String getEmail() { return email; } }
",1,PERPLEXITY,Write Java code using Optional to safely extract user email or return defaul,JAVA
,"class Solution {
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> inputMap = new HashMap<>();
// Construct HashMap as getting the employee from id is difficult in a list
for(Employee e : employees) {
inputMap.put(e.id, e);
}
return helper(inputMap, id);
}
private static int helper(Map<Integer, Employee> inputMap, int id) {
//Get the importance of the employee
int imp = inputMap.get(id).importance;
//Add importance of subordinates to employee importance
for(int subId : inputMap.get(id).subordinates) {
imp += helper(inputMap, subId);
}
return imp;
}
}",0,leetcode,NA,JAVA
,"import java.util.*;
import java.util.stream.Collectors;
public class GroupingExample {
public static Map<String, List<Employee>> groupByDept(List<Employee> employees) {
return employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
}
}
class Employee { private String department; public String getDepartment() { return department; } }
",1,PERPLEXITY,Use Java Collectors.groupingBy to group list of employees by department,JAVA
,"class MapSum {
Map<String, Integer> map;
public MapSum() {
map = new HashMap<>();
}
public void insert(String key, int val) {
map.put(key, val);
}
public int sum(String prefix) {
int sum = 0;
for (String key : map.keySet()) {
if (key.startsWith(prefix)) {
sum += map.get(key);
}
}
return sum;
}
}",0,leetcode,NA,JAVA
,"import java.util.List;
public class ParallelStreamExample {
public static long sumSquaresParallel(List<Integer> numbers) {
return numbers.parallelStream()
.mapToLong(n -> (long) n * n)
.sum();
}
}
",1,PERPLEXITY,Calculate sum of squares using parallel streams on a large list of numbers,JAVA
,"class MagicDictionary {
Set<String> originalWords;
Map<String, Integer> extensions;
public MagicDictionary() {
originalWords = new HashSet<>();
extensions = new HashMap<>();
}
public void buildDict(String[] dictionary) {
for (String word : dictionary) {
originalWords.add(word);
char[] str = word.toCharArray();
int n = str.length;
for (int i = 0; i < n; i++) {
char temp = str[i];
str[i] = '*';
String key = new String(str);
extensions.put(key, extensions.getOrDefault(key, 0) + 1);
str[i] = temp;
}
}
}
public boolean search(String searchWord) {
char[] str = searchWord.toCharArray();
int n = str.length;
for (int i = 0; i < n; i++) {
char temp = str[i];
str[i] = '*';
String key = new String(str);
if (extensions.containsKey(key)) {
// If count >= 2, then there's definitely a different word that maps to this pattern
// If count == 1, make sure it's not the same word
if (extensions.get(key) >= 2 || !originalWords.contains(searchWord)) {
return true;
}
}
str[i] = temp;
}
return false;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean isPossible(int[] nums) {
// freq: counts how many of each number are available to be used
Map<Integer, Integer> freq = new HashMap<>();
// want: counts how many sequences are currently ending at (x-1) and need 'x'
Map<Integer, Integer> want = new HashMap<>();
for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1);
for (int i : nums) {
if (freq.get(i) == 0) continue; // Already consumed by a previous 'new sequence' check
// Option 1: Try to extend an existing sequence
if (want.getOrDefault(i, 0) > 0) {
freq.put(i, freq.get(i) - 1);
want.put(i, want.get(i) - 1);
want.put(i + 1, want.getOrDefault(i + 1, 0) + 1);
}
// Option 2: Try to create a new sequence of length 3
else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) {
freq.put(i, freq.get(i) - 1);
freq.put(i + 1, freq.get(i + 1) - 1);
freq.put(i + 2, freq.get(i + 2) - 1);
// This sequence now ends at i+2, so it looks forward to i+3
want.put(i + 3, want.getOrDefault(i + 3, 0) + 1);
}
// Option 3: Impossible to use 'i' validly
else {
return false;
}
}
return true;
}
}",0,leetcode,NA,JAVA
,"public enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public static DayOfWeek[] values() {
return values();
}
public static DayOfWeek getByName(String name) {
for (DayOfWeek day : values()) {
if (day.name().equalsIgnoreCase(name)) return day;
}
throw new IllegalArgumentException(""Invalid day: "" + name);
}
}
",1,PERPLEXITY,Create a Java enum for days of week with a custom values method and getByName,JAVA
,"class Solution {
HashSet<Integer> set = new HashSet<>();
public boolean findTarget(TreeNode root, int k) {
// Base case: null node
if (root == null) return false;
// If complement is found, return true
if (set.contains(k - root.val)) return true;
// Otherwise, add current node value to the set
set.add(root.val);
// Recurse on left and right subtrees
return findTarget(root.left, k) || findTarget(root.right, k);
}
}",0,leetcode,NA,JAVA
,"public class ValidationException extends Exception {
public ValidationException(String message) { super(message); }
}
public class UserValidationException extends ValidationException {
public UserValidationException(String field) {
super(""Invalid "" + field + "" value provided"");
}
}
public class Validator {
public static void validateEmail(String email) throws UserValidationException {
if (!email.contains(""@"")) throw new UserValidationException(""email"");
}
}
",1,PERPLEXITY,Define a custom exception class hierarchy with validation exception in Java,JAVA
,"class Solution {
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
List<TreeNode> res=new ArrayList<>();
HashMap<String,Integer> hm=new HashMap<>();
helper(res,root,hm);
return res;
}
public String helper(List<TreeNode> res,TreeNode root,HashMap<String,Integer> hm){
if(root==null)
return """";
String left=helper(res,root.left,hm);
String right=helper(res,root.right,hm);
int currroot=root.val;
String stringformed=currroot+""$""+left+""$""+right;
if(hm.getOrDefault(stringformed,0)==1){
res.add(root);
}
hm.put(stringformed,hm.getOrDefault(stringformed,0)+1);
return stringformed;
}
}",0,leetcode,NA,JAVA
,"import java.lang.reflect.Field;
public class ReflectionUtil {
public static void setPrivateField(Object obj, String fieldName, Object value) throws Exception {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
}
public static Object getPrivateField(Object obj, String fieldName) throws Exception {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
}
}
",1,PERPLEXITY,Write Java reflection code to access and modify private fields dynamically.,JAVA
,"class Solution {
Trie root;
public String replaceWords(List<String> dictionary, String sentence) {
root = new Trie();
for(String word : dictionary){
insert(word);
}
StringBuilder result = new StringBuilder();
String [] input = sentence.split("" "");
for(String i : input){
result.append(search(i));
result.append("" "");
}
return result.toString().trim();
}
public String search(String word){
Trie node = root;
int j = 0;
for(char c : word.toCharArray()){
int i = c - 'a';
j++;
if(node.children[i] == null){
return word;
}else if(node.children[i].isEnd){
return word.substring(0, j);
}else{
node = node.children[i];
}
}
return word;
}
public void insert(String word){
Trie node = root;
for(char c: word.toCharArray()){
int i = c - 'a';
if(node.children[i] == null){
node.children[i] = new Trie();
}
node = node.children[i];
}
node.isEnd = true;
}
}
class Trie{
Trie [] children;
boolean isEnd;
public Trie(){
children = new Trie[26];
isEnd =false;
}
} ",0,leetcode,NA,JAVA
,"import java.util.List;
public class GenericUtils {
public static void printList(List<?> list) {
for (Object item : list) System.out.println(item);
}
public static void addNumbers(List<? super Integer> list) {
list.add(42);
}
public static double sum(List<? extends Number> numbers) {
double sum = 0;
for (Number n : numbers) sum += n.doubleValue();
return sum;
}
}
",1,PERPLEXITY,Create generic methods using wildcards for super and extends in Java collections,JAVA
,"
class Solution {
public int[] findErrorNums(int[] nums) {
int dup = -1, missing = -1;
for (int i = 1; i <= nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] == i) {
count++;
}
}
if (count == 2) {
dup = i;
} else if (count == 0) {
missing = i;
}
}
return new int[] {dup, missing};
}
}
",0,leetcode,NA,JAVA
,"import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecution {
String value() default """";
}
public class AnnotationProcessor {
public static void process(Object obj) throws Exception {
for (java.lang.reflect.Method m : obj.getClass().getMethods()) {
if (m.isAnnotationPresent(LogExecution.class)) {
System.out.println(""Logging: "" + m.getName());
}
}
}
}
",1,PERPLEXITY,Create a basic custom annotation with processor stub for runtime processing,JAVA
,"class Solution {
public int[] smallestRange(List<List<Integer>> nums) {
// Min-Heap: stores (value, list index, element index)
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
int curMax = Integer.MIN_VALUE;
// Initialize the heap with the first element of each list
for (int i = 0; i < nums.size(); i++) {
minHeap.offer(new int[]{nums.get(i).get(0), i, 0});
curMax = Math.max(curMax, nums.get(i).get(0));
}
// Track the smallest range
int[] smallRange = new int[]{0, Integer.MAX_VALUE};
while (true) {
// Get the minimum element from the heap
int[] curr = minHeap.poll();
int curMin = curr[0], listIdx = curr[1], elemIdx = curr[2];
// Update the smallest range if a better one is found
if (curMax - curMin < smallRange[1] - smallRange[0]) {
smallRange[0] = curMin;
smallRange[1] = curMax;
}
// Move to the next element in the same list
if (elemIdx + 1 < nums.get(listIdx).size()) {
int nextVal = nums.get(listIdx).get(elemIdx + 1);
minHeap.offer(new int[]{nextVal, listIdx, elemIdx + 1});
curMax = Math.max(curMax, nextVal);
} else {
// If any list is exhausted, stop
break;
}
}
return smallRange;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public boolean isSubsequence(String s1, String s2) {
int m = s1.length();
int n = s2.length();
int j=0,i=0;
while(i<m){
if(j>=n) return true;
if(s1.charAt(i)==s2.charAt(j)){
i++;
j++;
}
else i++;
}
if(j>=n) return true;
return false;
}
public int numMatchingSubseq(String s1, String[] words) {
int count = 0;
HashMap<String, Integer> map = new HashMap<>();
for (String w : words) map.put(w, map.getOrDefault(w, 0) + 1);
for(String s2 : map.keySet()){
if(isSubsequence(s1,s2)) count+=map.get(s2);
}
return count;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int leastInterval(char[] tasks, int n) {
int[] freq = new int[26];
for (char task : tasks) {
freq[task - 'A']++;
}
Arrays.sort(freq);
int chunk = freq[25] - 1;
int idle = chunk * n;
for (int i = 24; i >= 0; i--) {
idle -= Math.min(chunk, freq[i]);
}
return idle < 0 ? tasks.length : tasks.length + idle;
}
}",0,leetcode,NA,JAVA
,"class Solution {
public List<List<String>> findDuplicate(String[] paths) {
List<List<String>> al = new ArrayList<>();
HashMap<String, List<String>> hashmap = new HashMap<>();
for(String path : paths) {
String[] arr = path.split(""\\ "");
String dirPath = arr[0];
for(int i = 1; i < arr.length; i++) {
StringBuilder content = new StringBuilder();
int j = 0;
for(j = arr[i].length() - 2; j >= 0 && arr[i].charAt(j) != '('; j--) {
content.insert(0, arr[i].charAt(j));
}
String fileName = arr[i].substring(0, j);
hashmap.putIfAbsent(content.toString(), new ArrayList<>());
hashmap.get(content.toString()).add(dirPath + ""/"" + fileName);
}
}
for(String string : hashmap.keySet()) {
if(hashmap.get(string).size() >= 2) {
al.add(new ArrayList<>(hashmap.get(string)));
}
}
return al;
}
}",0,leetcode,NA,JAVA
,"public int evaluate(String expression)
{
return eval(expression, new HashMap<>());
}
private int eval(String expr, Map<String, Integer> scope)
{
// 1. If it's a number, return it directly
if (Character.isDigit(expr.charAt(0)) || expr.charAt(0) == '-')
return Integer.parseInt(expr);
// 2. If it's a variable, get its value from the scope
if (Character.isLowerCase(expr.charAt(0)) && !expr.startsWith(""(""))
return scope.get(expr); //e.g. scope={ ""x"": 2, ""y"": 3 } so return 2 for eval(x, scope)
// 3. Remove outer parentheses and tokenize the expression
expr=expr.substring(1, expr.length() - 1); // Remove outer parentheses
List<String> tokens = new ArrayList<>();
int balance=0, start=0;
for (int i=0; i<expr.length(); i++) {
char c=expr.charAt(i);
if (c=='(') balance++;
if (c==')') balance--;
if (balance==0 && (c==' '||i==expr.length()-1))
{//Splits tokens when we hit a space (c == ' ') or reach the last character (i == expr.length() - 1
tokens.add(expr.substring(start, i+(i==expr.length()-1?1:0)).trim()); //If the current character is the last one, extend the substring to include it (i + 1).
start=i+1;
}
}
//e.g. tokens = [""let"", ""x"", ""2"", ""(mult x (let x 3 y 4 (add x y)))""];
// 4. Parse operation and evaluate accordingly
String operation = tokens.get(0);
if (operation.equals(""add""))
return eval(tokens.get(1), scope) + eval(tokens.get(2), scope);
else if (operation.equals(""mult"")) //tokens = [""mult"", ""x"", ""(let x 3 y 4 (add x y))""];
return eval(tokens.get(1), scope) * eval(tokens.get(2), scope); //get x val * get val of the other expr
else // ""let"" operation
{
Map<String, Integer> newScope = new HashMap<>(scope); // Create a new scope // Scope: {}
for (int i=1;i<tokens.size()-1;i+=2)
newScope.put(tokens.get(i), eval(tokens.get(i+1), newScope)); // Assign variables - newScope.put(""x"", eval(""2"", newScope)); // x = 2
return eval(tokens.get(tokens.size()-1), newScope); // Evaluate the final expression - eval(""(mult x (let x 3 y 4 (add x y)))"", newScope);
}
}",0,leetcode,NA,JAVA
,"import java.net.http.*;
import java.net.URI;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RestClient {
public static <T> T getJson(String url, Class<T> clazz) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(resp.body(), clazz);
}
}
",1,PERPLEXITY,Write Java code using HttpClient to call REST API and parse JSON response.,JAVA
,"class Solution {
public String countOfAtoms(String formula) {
int n = formula.length();
Map<String, Integer> result_counter = new HashMap<>();
Deque<Map<String, Integer>> parenthesis_stack = new ArrayDeque<>();
int cur_ind = 0;
while (cur_ind < n) {
char cur_char = formula.charAt(cur_ind);
if (cur_char == '(') {
cur_ind++;
parenthesis_stack.push(new HashMap<>());
continue;
}
if (cur_char == ')') {
StringBuilder mult_str = new StringBuilder();
cur_ind++;
while (cur_ind < n && Character.isDigit(formula.charAt(cur_ind))) {
mult_str.append(formula.charAt(cur_ind));
cur_ind++;
}
int mult = mult_str.length() == 0 ? 1 : Integer.parseInt(mult_str.toString());
Map<String, Integer> last_counter = parenthesis_stack.pop();
Map<String, Integer> target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek();
for (Map.Entry<String, Integer> entry : last_counter.entrySet()) {
target.put(entry.getKey(), target.getOrDefault(entry.getKey(), 0) + entry.getValue() * mult);
}
continue;
}
StringBuilder cur_elem = new StringBuilder();
StringBuilder cur_counter_str = new StringBuilder();
Map<String, Integer> target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek();
while (cur_ind < n && formula.charAt(cur_ind) != '(' && formula.charAt(cur_ind) != ')') {
if (Character.isAlphabetic(formula.charAt(cur_ind))) {
if (Character.isUpperCase(formula.charAt(cur_ind)) && cur_elem.length() > 0) {
target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString())));
cur_elem = new StringBuilder();
cur_counter_str = new StringBuilder();
}
cur_elem.append(formula.charAt(cur_ind));
} else {
cur_counter_str.append(formula.charAt(cur_ind));
}
cur_ind++;
}
target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString())));
}
List<String> parts = new ArrayList<>();
for (Map.Entry<String, Integer> entry : result_counter.entrySet()) {
parts.add(entry.getKey() + (entry.getValue() == 1 ? """" : entry.getValue()));
}
Collections.sort(parts);
StringBuilder result = new StringBuilder();
for (String part : parts) {
result.append(part);
}
return result.toString();
}
}",0,leetcode,NA,JAVA
,"import java.sql.*;
import java.util.*;
public class JdbcPool {
private List<Connection> pool = new ArrayList<>();
private int maxSize;
public JdbcPool(int maxSize) { this.maxSize = maxSize; }
public Connection getConnection() throws SQLException {
if (pool.isEmpty()) {
return DriverManager.getConnection(""jdbc:h2:mem:test"");
}
return pool.remove(0);
}
public void returnConnection(Connection conn) {
pool.add(conn);
}
}
",1,PERPLEXITY,Implement a simple JDBC connection pool manager in Java.,JAVA
,"class Solution {
/*
* Disjoint Set Union over emails.
* Each unique email is treated as a node.
*/
static class DSU {
int[] parent;
int[] size;
/*
* Initializes DSU with each email in its own set.
*/
DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
/*
* Returns representative of the email's component.
* Uses path compression to keep tree shallow.
*/
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
/*
* Merges two email components using union by size.
*/
void union(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa == pb)
return;
if (size[pa] < size[pb]) {
parent[pa] = pb;
size[pb] += size[pa];
} else {
parent[pb] = pa;
size[pa] += size[pb];
}
}
}
/*
* Merges accounts that share at least one common email.
* Emails in the result are sorted lexicographically.
*/
public List<List<String>> accountsMerge(List<List<String>> accounts) {
/*
* Maps each email to a unique DSU index.
* Also keeps track of the owner name for each email.
*/
Map<String, Integer> emailIndex = new HashMap<>();
Map<String, String> emailName = new HashMap<>();
int idx = 0;
for (List<String> acc : accounts) {
String name = acc.get(0);
for (int i = 1; i < acc.size(); i++) {
String email = acc.get(i);
if (!emailIndex.containsKey(email)) {
emailIndex.put(email, idx++);
emailName.put(email, name);
}
}
}
DSU dsu = new DSU(idx);
/*
* Union all emails belonging to the same account.
*/
for (List<String> acc : accounts) {
int firstEmail = emailIndex.get(acc.get(1));
for (int i = 2; i < acc.size(); i++) {
dsu.union(firstEmail, emailIndex.get(acc.get(i)));
}
}
/*
* Groups emails by their DSU representative.
*/
Map<Integer, List<String>> groups = new HashMap<>();
for (String email : emailIndex.keySet()) {
int root = dsu.find(emailIndex.get(email));
groups.computeIfAbsent(root, k -> new ArrayList<>()).add(email);
}
/*
* Builds the final merged account list.
*/
List<List<String>> result = new ArrayList<>();
for (List<String> emails : groups.values()) {
Collections.sort(emails);
List<String> merged = new ArrayList<>();
merged.add(emailName.get(emails.get(0)));
merged.addAll(emails);
result.add(merged);
}
return result;
}
}",0,leetcode,NA,JAVA
,"import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080);
while (true) {
Socket client = server.accept();
new Thread(() -> {
try (BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
String line;
while ((line = in.readLine()) != null) {
out.println(""Echo: "" + line);
}
} catch (IOException e) {}
}).start();
}
}
}
",1,PERPLEXITY,Create a simple TCP socket server in Java that echoes client messages,JAVA
,"class Solution {
private TreeNode root;
private String result = """";
public String longestWord(String[] words) {
root = new TreeNode();
for (String w : words)
insert(w);
dfs(root);
return result;
}
private void dfs(TreeNode node) {
if (node == null)
return;
if (node.word != null) {
if (node.word.length() > result.length())
result = node.word;
else if (node.word.length() == result.length() && node.word.compareTo(result) < 0)
result = node.word;
}
for (TreeNode child : node.children)
if (child != null && child.word != null)
dfs(child);
}
private void insert(String word) {
TreeNode current = root;
for (char c : word.toCharArray()) {
if (current.children[c - 'a'] == null)
current.children[c - 'a'] = new TreeNode();
current = current.children[c - 'a'];
}
current.word = word;
}
}
class TreeNode {
TreeNode[] children = new TreeNode[26];
String word;
TreeNode () {}
}",0,leetcode,NA,JAVA
,"import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.*;
@Mojo(name = ""generate-props"", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class PropertiesGeneratorMojo extends AbstractMojo {
@Parameter(defaultValue = ""${project.build.directory}"")
private String outputDirectory;
public void execute() throws MojoExecutionException {
getLog().info(""Generating properties file..."");
// Generate properties logic here
getLog().info(""Properties file generated successfully"");
}
}
",1,PERPLEXITY,Write a basic Maven plugin MOJO class that generates a properties file.,JAVA
,"class Solution {
List <int[]> dividedRange;
int numberOfDivisions = 0;
Random rand;
public Solution(int n, int[] arr) {
Arrays.sort(arr);
rand = new Random();
dividedRange = new ArrayList <>();
int start = 0, end = 0;
for (int i = 0; i < arr.length; i++) {
end = arr[i] - 1;
if (start > end) {
start = arr[i] + 1;
continue;
}
dividedRange.add(new int[]{start, end});
start = arr[i] + 1;
}
if (start < n) {
dividedRange.add(new int[]{start, n-1});
}
numberOfDivisions = dividedRange.size();
}
public int pick() {
int pickedDivision = rand.nextInt(numberOfDivisions);
int start = dividedRange.get(pickedDivision)[0];
int end = dividedRange.get(pickedDivision)[1];
return rand.nextInt(end - start + 1) + start;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(n, blacklist);
* int param_1 = obj.pick();
*/",0,leetcode,NA,JAVA
,"class Node {
int key;
int val;
Node next;
Node(int key, int val) {
this.key = key;
this.val = val;
this.next = null;
}
}
class MyHashMap {
private Node[] map;
public MyHashMap() {
map = new Node[1000];
for (int i = 0; i < 1000; i++) {
map[i] = new Node(-1, -1);
}
}
public void put(int key, int value) {
int hash = hash(key);
Node cur = map[hash];
while (cur.next != null) {
if (cur.next.key == key) {
cur.next.val = value;
return;
}
cur = cur.next;
}
cur.next = new Node(key, value);
}
public int get(int key) {
int hash = hash(key);
Node cur = map[hash].next;
while (cur != null) {
if (cur.key == key)
return cur.val;
cur = cur.next;
}
return -1;
}
public void remove(int key) {
int hash = hash(key);
Node cur = map[hash];
while (cur.next != null) {
if (cur.next.key == key) {
cur.next = cur.next.next;
return;
}
cur = cur.next;
}
}
private int hash(int key) {
return key % 1000;
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/",0,leetcode,NA,JAVA
,"import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(""/api/users"")
public class UserController {
@GetMapping(""/{id}"")
public String getUser(@PathVariable Long id) {
return ""User: "" + id;
}
@PostMapping
public String createUser(@RequestBody String name) {
return ""Created user: "" + name;
}
}
",1,PERPLEXITY,"Create a basic Spring Boot REST controller with GET, POST endpoints.",JAVA
,"package SystemDesign.Easy;
public class _705_Design_HashSet {
// Custom HashSet implementation using bitset
private static class MyHashSet {
// Each int holds 32 bits → supports keys up to 10^6
private final int[] set;
public MyHashSet() {
// 10^6 / 32 ≈ 31250
this.set = new int[31251];
}
public void add(int key) {
set[key / 32] |= getMask(key);
}
public void remove(int key) {
if (contains(key)) {
set[key / 32] ^= getMask(key);
}
}
public boolean contains(int key) {
return (set[key / 32] & getMask(key)) != 0;
}
// Returns a bit mask for the given key
private int getMask(int key) {
return 1 << (key % 32);
}
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int findShortestSubArray(int[] nums) {
HashMap<Integer, Integer> count = new HashMap<>();
HashMap<Integer, Integer> first = new HashMap<>();
HashMap<Integer, Integer> last = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
count.put(num, count.getOrDefault(num, 0) + 1);
if (!first.containsKey(num)) {
first.put(num, i);
}
last.put(num, i);
}
int degree = 0;
for (int val : count.values()) {
degree = Math.max(degree, val);
}
int ans = nums.length;
for (int key : count.keySet()) {
if (count.get(key) == degree) {
ans = Math.min(ans, last.get(key) - first.get(key) + 1);
}
}
return ans;
}
}",0,leetcode,NA,JAVA
,"import java.util.HashMap;
class Solution {
public String customSortString(String order, String s) {
StringBuilder result = new StringBuilder();
HashMap<Character, Integer> mp = new HashMap<>();
for (char c : s.toCharArray()) {
mp.put(c, mp.getOrDefault(c, 0) + 1);
}
for (char c : order.toCharArray()) {
if (mp.containsKey(c)) {
result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c))));
mp.remove(c);
}
}
for (char c : mp.keySet()) {
result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c))));
}
return result.toString();
}
}",0,leetcode,NA,JAVA
,"class Solution {
public int numRabbits(int[] answers) {
Map<Integer, Integer> mpp = new HashMap<>();
for (int i : answers) mpp.put(i, mpp.getOrDefault(i, 0) + 1);
int total = 0;
for (Map.Entry<Integer, Integer> p : mpp.entrySet())
total += Math.ceil((double)p.getValue() / (p.getKey() + 1)) * (p.getKey() + 1);
return total;
}
}",0,leetcode,NA,JAVA