Pergunta de entrevista da empresa ServiceTitan

Need to realize FIFO (queue) with an option of node expiration time. Please write the code.

Resposta da entrevista

Sigiloso

14 de jan. de 2025

using System; using System.Collections; using System.Collections.Generic; using TEST; namespace TEST { public class Node { public Node(T? value, DateTime? exprirationDateTime = null) { this.Id = Guid.NewGuid(); this.Value = value; this.ExprirationDateTime = exprirationDateTime; } public Guid Id { get; } public T? Value { get; set; } public DateTime? ExprirationDateTime { get; set; } internal Node? Next { get; set; } } internal interface IFIFOEngine { Node Peek(); Node Pop(); bool Push(Node node); } internal class FIFOEngine : IFIFOEngine, IEnumerable> { private Node? _thresholder = null; private Node? _last = null; IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator> GetEnumerator() { if (_thresholder == null) { throw new InvalidOperationException(String.Format("The operation has failed.{0}The queue is empty!", Environment.NewLine)); } var current = _thresholder; while (current is not null) { yield return current; current = current.Next; } } public Node Peek() { if (_thresholder is null) { throw new InvalidOperationException(String.Format("The operation has failed.{0}The queue is empty!", Environment.NewLine)); } RemoveExpiredNodes(); return _thresholder; } public Node Pop() { if (_thresholder is null) { throw new InvalidOperationException(String.Format("The operation has failed.{0}The queue is empty!", Environment.NewLine)); } RemoveExpiredNodes(); var tmp = _thresholder; _thresholder = _thresholder.Next; if (_thresholder is null) { _last = null; } tmp.Next = null; return tmp; } public bool Push(Node node) { if (node is null) { throw new ArgumentNullException(String.Format("The operation has failed.{0}The item {1} is null!", Environment.NewLine, nameof(node))); } if (_thresholder is null) { _thresholder = _last = node; return true; } _last!.Next = node; _last = node; return true; } private void RemoveExpiredNodes() { while (_thresholder != null && _thresholder.ExprirationDateTime.HasValue && _thresholder.ExprirationDateTime.Value < DateTime.Now) { var tmp = _thresholder; _thresholder = _thresholder.Next; if (_thresholder == null) { _last = null; } tmp.Next = null; } } } } public partial class Program { public static void Main() { var node1 = new Node("Test1"); var node2 = new Node("Test2", DateTime.Now.AddMinutes(1)); var node3 = new Node(null, DateTime.Now.AddMinutes(2)); FIFOEngine queue = new FIFOEngine(); queue.Push(node1); queue.Push(node2); queue.Push(node3); var t = queue.Peek(); queue.Pop(); t = queue.Peek(); foreach (var node in queue) { var z = node.Value; } } }